Encrypt with Node.js Crypto module and decrypt with Java (in Android app)

前端 未结 4 1388
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 22:26

Looking for a way to encrypt data (mainly strings) in node and decrypt in an android app (java).

Have successfully done so in each one (encrypt/decrypt in node, and

4条回答
  •  借酒劲吻你
    2020-11-29 23:27

    The example from previous answers did not work for me when trying on Java SE since Java 7 complains that "AES/ECB/PKCS7Padding" can not be used.

    This however worked:

    to encrypt:

    var crypto = require('crypto')
    var cipher = crypto.createCipher('aes-128-ecb','somepassword')
    var text = "the big brown fox jumped over the fence"
    var crypted = cipher.update(text,'utf-8','hex')
    crypted += cipher.final('hex')
    //now crypted contains the hex representation of the ciphertext
    

    to decrypt:

    private static String decrypt(String seed, String encrypted) throws Exception {
        byte[] keyb = seed.getBytes("UTF-8");
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(keyb);
        SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");
        Cipher dcipher = Cipher.getInstance("AES");
        dcipher.init(Cipher.DECRYPT_MODE, skey);
    
        byte[] clearbyte = dcipher.doFinal(toByte(encrypted));
        return new String(clearbyte);
    }
    
    private static byte[] toByte(String hexString) {
        int len = hexString.length()/2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++) {
            result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
        }
        return result;
    }
    

提交回复
热议问题