android加密解密算法之3DES算法用例

来源:互联网 发布:排列组合公式c快速算法 编辑:程序博客网 时间:2024/05/11 14:00

android加密算法很多:DES ,AES,3DES等等。详情请google,baidu。

des的使用安全行很低,再次我们详细了解下3DES.

3DES顾名思义,就是对des加密算法进行得改进,对每个数据进行了3次des加密,降低了破解的难度,从而提高数据的安全性。

首先写一个utils工具,直接可以使用

import java.io.UnsupportedEncodingException;import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;/* 如果我们要使用3DES加密,需要以下几个步骤 ①传入共同约定的密钥(keyBytes)以及算法(Algorithm),来构建SecretKey密钥对象 SecretKey deskey = new SecretKeySpec(keyBytes, Algorithm);     ②根据算法实例化Cipher对象。它负责加密/解密 Cipher c1 = Cipher.getInstance(Algorithm);     ③传入加密/解密模式以及SecretKey密钥对象,实例化Cipher对象 c1.init(Cipher.ENCRYPT_MODE, deskey);     ④传入字节数组,调用Cipher.doFinal()方法,实现加密/解密,并返回一个byte字节数组 c1.doFinal(src); */public class DES3Utils {// 定义加密算法private static final String Algorithm = "DESede";// 加密密钥private static final String PASSWORD_CRYPT_KEY = "dlzh1991";// 加密 src为源数据的字节数组public static byte[] encryptMode(byte[] src) {try {// 生成密钥SecretKey deskey = new SecretKeySpec(build3Deskey(PASSWORD_CRYPT_KEY), Algorithm);// 实例化cipherCipher cipher = Cipher.getInstance(Algorithm);cipher.init(Cipher.ENCRYPT_MODE, deskey);return cipher.doFinal(src);} catch (Exception e) {e.printStackTrace();}return null;}// 解密函数public static byte[] decryptMode(byte[] src) {SecretKey deskey;try {deskey = new SecretKeySpec(build3Deskey(PASSWORD_CRYPT_KEY),Algorithm);Cipher cipher = Cipher.getInstance(Algorithm);cipher.init(Cipher.DECRYPT_MODE, deskey);return cipher.doFinal(src);} catch (Exception e) {e.printStackTrace();}return null;}// 根据字符串生成密钥24位的字节数组public static byte[] build3Deskey(String keyStr) throws Exception {byte[] key = new byte[24];byte[] temp = keyStr.getBytes("UTF-8");if (key.length > temp.length) {System.arraycopy(temp, 0, key, 0, temp.length);} else {System.arraycopy(temp, 0, key, 0, key.length);}return key;}}
然后我们写一个test类使用utils进行加密解密STRING
package com.example.des;public class DesTest {    //android数据加密和解密算法:DES 3DES AESpublic static void main(String[] args) {String msg = "杜立志dlzh1991";System.out.println("待加密数据:" + msg.length());// 加密byte[] secretArr = DES3Utils.encryptMode(msg.getBytes());System.out.println("加密之后:" + secretArr + "--转化字符串:"+ new String(secretArr));// 解密byte[] secreArr2 = DES3Utils.decryptMode(secretArr);System.out.println("解密之后:" + secreArr2 + "--转化字符串:"+ new String(secreArr2));}}
最近后台打印结果:



0 0
原创粉丝点击