Совместимость шифрования и дешифрования aes gcm - PullRequest
0 голосов
/ 02 ноября 2018

Пожалуйста, поделитесь рабочим кодом шифрования в узле js и расшифровкой в ​​java AES / GCM / NoPadding

В Узел JS :

function createCipherCommon(text, alg, key, iv) {
    var cipher = crypto.createCipheriv(alg, key, iv);
    cipher.setAAD(Buffer.from("aad", 'utf8'));
    return {
        enc: cipher.update(text, 'utf8', 'base64') + cipher.final('base64'),
        tag: cipher.getAuthTag().toString('base64')
    };
}

В Java приведенный ниже код дает javax.crypto.AEADBadTagException: несоответствие тега!

public static String createDecipherCommon(byte[] text, byte[] key, String iv, String tag) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, NoSuchProviderException, InvalidAlgorithmParameterException, UnsupportedEncodingException, DecoderException {
        byte[] ivBytes = Base64.getDecoder().decode(iv.getBytes());
        byte[] tagBytes = Base64.getDecoder().decode(tag.getBytes());
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, ivBytes, 0, ivBytes.length));
        cipher.updateAAD("aad".getBytes());
        return new String(cipher.doFinal(text, 0, text.length));
    }

1 Ответ

0 голосов
/ 02 ноября 2018

В Node js я внес эти изменения и теперь он работает нормально:

function createCipherCommon(text, alg, key, iv) {
    var cipher = crypto.createCipheriv(alg, key, iv);
    cipher.setAAD(Buffer.from("aad", 'utf8'));
    return {
        encwithtag: Buffer.concat([cipher.update(text, 'utf8'), cipher.final(), cipher.getAuthTag()]).toString('base64')
    };
}

В Java , без изменений

public static String createDecipherCommon(byte[] text, byte[] key, String iv, String tag) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, NoSuchProviderException, InvalidAlgorithmParameterException, UnsupportedEncodingException, DecoderException {
        byte[] ivBytes = Base64.getDecoder().decode(iv.getBytes());
        byte[] tagBytes = Base64.getDecoder().decode(tag.getBytes());
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, ivBytes, 0, ivBytes.length));
        cipher.updateAAD("aad".getBytes());
        return new String(cipher.doFinal(text, 0, text.length));
    }
...