使用cipher可以很容易的实现3des加密,但是跟其他平台开发的3des加密对接来说,通常会有一些问题。基本的程序如下:
public static byte[] desEncrypt(String message, String key) throws Exception {
Cipher cipher = Cipher.getInstance("DESede");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(message.getBytes("UTF-8"));
』
我们跟其他平台对接发现对同样输入加密以后结果不同,看看jdk的文档,有如下描述:
A transformation is a string that describes the operation (or set of operations) to be performed on the given input, to produce some output.
A transformation is of the form:
- "algorithm/mode/padding" or
- "algorithm"
(in the latter case, provider-specific default values for the mode and padding scheme are used).
根据前面的代码,我们已经选择了正确的算法,那么加密不同的原因应该就是mode和padding了。
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才能保证通信。
本文探讨了使用Java实现3DES加密时遇到的跨平台一致性问题。通过分析JDK文档,指出了加密模式(mode)和填充方式(padding)设置的重要性,并强调了在不同平台上进行3DES加密时必须统一这些参数。
307

被折叠的 条评论
为什么被折叠?



