使用cipher可以很容易的实现3des加密,但是跟其他平台开发的3des加密对接来说,通常会有一些问题。最近 一个项目java
要调用.net的WEB
SERVICE,数据采用3DES加密,涉及到两种语言3DES一致性的问题,这里的KEY采用Base64编码,便用分发,因为Java的Byte范围为-128至127,c#的Byte范围是0-255
需要注意的是确定Mode和Padding,关于这两个的意思可以搜索3DES算法相关文章
一个是C#采用ECB Mode,PKCS7 Padding,Java采用ECB Mode,PKCS5Padding
Padding
java的3DES加密代码:
public
static String DesAndBase64Encrypt(String message, String key)
throws Exception {
String algorithm=”DESede/ECB/PKCS5Padding”;
Cipher cipher = Cipher.getInstance(algorithm);
//
byte[] keybyte=new
BASE64Decoder().decodeBuffer(“YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4″);
byte[] keybyte=key.getBytes(“utf-8″);
DESedeKeySpec desKeySpec = new DESedeKeySpec(keybyte);
SecretKeyFactory keyFactory =
SecretKeyFactory.getInstance(“desede”);
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
String result=new
sun.misc.BASE64Encoder().encode(cipher.doFinal(message.getBytes(“UTF-8″)));
return result;
}
he SunJCE provider uses ECB as the default mode, and
PKCS5Padding as the default padding scheme for DES, DES-EDE and
Blowfish ciphers. This means that in the case of the SunJCE
provider,
Cipher c1 =
Cipher.getInstance(“DES/ECB/PKCS5Padding”);
and
Cipher c1 = Cipher.getInstance(“DES”);
are equivalent statements.
对于其他语言开发的3des,一定要采用相同的mode和padding才能保证通信。