Encrypt string in java, decrypt in node.js, error: bad decrypt

后端 未结 2 1475
春和景丽
春和景丽 2021-02-09 07:26

I\'m trying to encrypt a string in java, send it to my node.js server, and decrypt it. However, when I try to do this I get keep getting errors when trying to decrypt.

2条回答
  •  梦谈多话
    2021-02-09 08:07

    When you create the decipher object on the node server, you are passing a password rather than an actual key. In order to specify the actual key, you need to use crypto.createDecipheriv(), but this requires an actual IV (this example uses 8 null bytes, but that's not recommended for real encryption; Initialization Vector on wikipedia)

    I was able to get your example working by explicitly specifying padding, block mode, and IV:

    String privateKey = "someprivatekey";
    String data = "dataToEncrypt";
    
    DESKeySpec keySpec = new DESKeySpec(privateKey.getBytes("UTF-8"));
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey key = keyFactory.generateSecret(keySpec);
    
    byte[] dataToBytes = data.getBytes("UTF-8");      
    
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); 
    cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(new byte[8]));
    
    // send this string to server 
    String encryptedStr = Base64.encodeToString(cipher.doFinal(dataToBytes), 0);
    

    The decryption version also explicitly specifies the block mode (des-cbc), and correctly truncates the key text to the first 8 bytes:

    var privateKey = 'someprivatekey';
    var textToDecipher = '9Y8GTNxhQkKSIm5pmH91VA=='; // Text "dataToEncrypt" encrypted using DES using CBC and PKCS5 padding with the key "someprivatekey"
    
    var iv = new Buffer(8);
    iv.fill(0);
    
    var decipher = crypto.createDecipheriv('des-cbc', privateKey.substr(0,8), iv);
    var dec = decipher.update(textToDecipher, 'base64', 'utf8');
    dec += decipher.final('utf8');
    console.log('deciphered: ' + dec);
    

提交回复
热议问题