您的位置:首页 > 移动开发 > Android开发

Java/Android中的3DES加密

2016-06-28 22:17 239 查看
3DES(或称为Triple DES)是通过DES进行3次加密,密钥的长度为DES的密钥3倍,加密后的数据长度与DES加密长度相同。安全方面相对于DES加密更加安全,不容易被破解。

代码:

/* 定义加密方式, DESede:加密算法; ECB:工作模式 ; NOPadding:填充方式 */
private static final String Algorithm = "DESede/ECB/NOPadding";

/**
* 说明 :3DES加密
*
* @param keybyte 密钥
* @return
* @key data 明文
*/
public static byte[] encryptMode(byte[] data, byte[] keybyte) {
try {
// 生成密钥
SecretKey deskey = new SecretKeySpec(keybyte, "DESede");
// 加密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
byte result[] = c1.doFinal(data);
return result;
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (Exception e3) {
e3.printStackTrace();
}
return null;
}

/**
* 说明 :3DES解密
*
* @param data 密文
* @param keybyte 密钥
* @return
*/

public static byte[] decryptMode(byte[] data, byte[] keybyte) {
try {
// 生成密钥
SecretKey deskey = new SecretKeySpec(keybyte, "DESede");
// 解密
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE, deskey);
byte[] result = c1.doFinal(data);
return result;

} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (Exception e3) {
e3.printStackTrace();
}
return null;
}

大家可以根据需要将byte[]转换成16进制或者转换为Base64格式,如需要加密字符串最后将byte[]转换为Base64格式,不然会出现乱码;

加密中文字符串流程:

1、字符串转换为Byte数组

2、将Byte数组加密

3、将加密之后的Byte数组转换为Base64格式

解密:

1、将Base64格式字符串转换为Byte数组

2、将Byte数组解密

3、将解密后的Byte数组转换为String格式

Byte[]转16进制字符串

/**
* byte数组转换为16进制字符串
*
* @param bts 数据源
* @return 16进制字符串
*/
public static String bytes2Hex(byte[] bts) {
String des = "";
String tmp = null;
for (int i = 0; i < bts.length; i++) {
tmp = (Integer.toHexString(bts[i] & 0xFF));
if (tmp.length() == 1) {
des += "0";
}
des += tmp;
}
return des;
}
16进制转byte[]

/**
* 将16进制转换为byte数组
*
* @param hexString 16进制字符串
* @return byte数组
*/

public static byte[] toByte(String hexString) {
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
16).byteValue();
return result;
}
Byte[]转Base64格式

String encrypedValue = Base64.encodeToString(
data, Base64.DEFAULT);

Base64转Byte[]格式

byte[] data= Base64.decode(text, Base64.DEFAULT);

String 转byte[]格式

byte[] data= str.getBytes("UTF8");
Byte[]转String格式
String str= new String(data);


生成密钥方法:

KeyGenerator kg = KeyGenerator.getInstance("DES");
Key key = kg.generateKey();
byte[] keyBytes = ((Key) key).getEncoded();
String Keystr = DES.bytes2Hex(keyBytes);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息