public static String encryptKey(String mainKey,String plainKey){
String encryptKey = "";
try{
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
String Algorithm = "DESede/ECB/NoPadding";
byte[] hb = hex2byte(mainKey.getBytes());
byte[] k = new byte[24];
System.arraycopy(hb,0,k,0,16);
System.arraycopy(hb,0,k,16,8);
SecretKey deskey = new SecretKeySpec(k, Algorithm);
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
encryptKey = byte2hex(c1.doFinal(hex2byte(plainKey.getBytes())));
}catch(Exception e){
e.printStackTrace();
}
return encryptKey;
}
public static String byte2hex(byte[] b) { String hs = ""; String stmp = ""; for (int n = 0; n < b.length; n++) { stmp = Integer.toHexString(b[n] & 0xFF); if (stmp.length() == 1) hs += ("0" + stmp); else hs += stmp; } return hs.toUpperCase(); }
3DES的加密密钥长度要求是24个字节,本例中因为给定的密钥只有16个字节,所以需要填补至24个字节。其中"DESede/ECB/NoPadding",除此之外,3DES还支持"DESede/CBC/PKCS5Padding"模式。
此代码中使用了Bouncy Castle密码包,需要自行下载,下载地址:http://www.bouncycastle.org/latest_releases.html