Java Triple DES encryption with 2 different keys

时光总嘲笑我的痴心妄想 提交于 2019-12-04 21:50:58

Why not just use the included DESede algorithm?

Change all your DES code instances to DESede and change your Key Generation method to as such:

public static SecretKey generateDESkey() {
    KeyGenerator keyGen = null;
    try {
        keyGen = KeyGenerator.getInstance("DESede");
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
    }
    keyGen.init(112); // key length 112 for two keys, 168 for three keys
    SecretKey secretKey = keyGen.generateKey();
    return secretKey;
}

Note how the getInstance() method is now supplied with DESede and the key size has been increased to 112 (168 for three keys).

Change your Cipher instances from:

Cipher.getInstance("DES/ECB/PKCS5Padding");

to

Cipher.getInstance("DESede/ECB/PKCS5Padding");

And you are set.

You are converting arbitrary bytes to Strings, which is corrupting them. work entirely with bytes. if you need to convert the encrypted data to a String, then use Base64 encoding.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!