AES encryption in javascript and decrypting in java

后端 未结 3 1818
旧巷少年郎
旧巷少年郎 2020-12-10 10:20

I have an excisting webservice which encrypts and decrypts with AES, now i have to encrypt in the same way as java but in javascript. I have read all the topics about doing

相关标签:
3条回答
  • 2020-12-10 10:28

    To decrypt hash generated using JAVA AES/ECB/PKCS5Padding, you need to create a decrypt cipher also with padding in js(nodejs).

    const crypto = require('crypto');
    function decrypt(data){
      var decipher = crypto.createCipheriv("aes-128-ecb", 'SAME_KEY_AS_JAVA', '');
      var dec = decipher.update(data,'base64','utf8');
      dec += decipher.final('utf8');
      return dec
    }
    
    0 讨论(0)
  • 2020-12-10 10:41

    You are looking at the encryption algorithm only but you have care for the block mode and padding too, otherwise you will not create compatible results. According to code.google.com CryptoJS has the defaults of CBC and PKCS7 while your Java code uses ECB and PKCS5.

    You have to bring that to match. You can setup CryptoJS to use ECB. Regarding the padding it’s more tricky as CryptoJS does not list PKCS5 as supported, and Java does not list PKCS7, in fact, it lists very little, so it might be implementation depended which padding algorithms the AES provider supports, but at least NoPadding is supported by both, Java and CryptoJS.

    0 讨论(0)
  • 2020-12-10 10:42

    Here is working solution to implement "AES/ECB/PKCS5Padding" but in JavaScript (Node.js) using ezcrypto module

    const Crypto = require('ezcrypto').Crypto;
    let whatToEncryptAsUtf8 = Crypto.charenc.UTF8.stringToBytes(whatToEncrypt);
    let keyAsUtf8 = Crypto.charenc.UTF8.stringToBytes(key);
    let encrypted = Crypto.AES.encrypt(whatToEncryptAsUtf8, keyAsUtf8, {
      mode: new Crypto.mode.ECB(Crypto.pad.pkcs7)
    });
    
    0 讨论(0)
提交回复
热议问题