首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法解密用AES-GCM-256加密的节点中的数据

无法解密用AES-GCM-256加密的节点中的数据
EN

Stack Overflow用户
提问于 2019-09-27 08:03:32
回答 1查看 1.5K关注 0票数 2

我试图在node.js中创建一个API来解密使用AES-GCM-256 algo创建的输入,我在JAVA中使用相同的algo加密代码,但是我无法使用node.js解密它。

我尝试过许多方法,但我可能被卡在标记部分了&我得到了错误“不支持的状态或无法验证数据”。

我的Java代码:

代码语言:javascript
复制
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
​
public class AES256GCMAlgo {
​
​
        static String plainText = "This is a plain text which need to be encrypted by Java AES 256 GCM Encryption Algorithm";
        public static final int AES_KEY_SIZE = 256;
        public static final int GCM_IV_LENGTH = 12;
        public static final int GCM_TAG_LENGTH = 16;
​
        public static void main(String[] args) throws Exception
        {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(AES_KEY_SIZE);
​
            // Generate Key
            SecretKey key = keyGenerator.generateKey();
            byte[] IV = new byte[GCM_IV_LENGTH];
            SecureRandom random = new SecureRandom();
            random.nextBytes(IV);
​
            byte[] encoded = key.getEncoded();
            String output = Base64.getEncoder().withoutPadding().encodeToString(encoded);
            System.out.println("Keep it secret, keep it safe! " + output);
​
​
            String ivoutput = Base64.getEncoder().withoutPadding().encodeToString(IV);
            System.out.println("Keep ivoutput secret, keep it safe! " + ivoutput);
​
            System.out.println("Original Text : " + plainText);
​
            byte[] cipherText = encrypt(plainText.getBytes(), key, IV);
​
            byte[] tagVal = Arrays.copyOfRange(cipherText, cipherText.length - (128 / Byte.SIZE), cipherText.length);
​
            System.out.println("Encrypted Text : " + Base64.getEncoder().encodeToString(cipherText));
​
            System.out.println("Tag Text : " + Base64.getEncoder().encodeToString(tagVal));
​
​
            String input = output ;
            byte[] deencoded = Base64.getDecoder().decode(output);
            SecretKey aesKey = new SecretKeySpec(deencoded, "AES");
​
            String ivinput = ivoutput;
            byte[] ivdeencoded = Base64.getDecoder().decode(ivinput);
​
            String decryptedText = decrypt(cipherText, aesKey, ivdeencoded);
            System.out.println("DeCrypted Text : " + decryptedText);
        }
​
        public static byte[] encrypt(byte[] plaintext, SecretKey key, byte[] IV) throws Exception
        {
            // Get Cipher Instance
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
​
            // Create SecretKeySpec
            SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");
​
            // Create GCMParameterSpec
            GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, IV);
​
            // Initialize Cipher for ENCRYPT_MODE
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);
​
            // Perform Encryption
            byte[] cipherText = cipher.doFinal(plaintext);
​
​
​
            return cipherText;
        }
​
        public static String decrypt(byte[] cipherText, SecretKey key, byte[] IV) throws Exception
        {
            // Get Cipher Instance
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
​
            // Create SecretKeySpec
            SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");
​
            // Create GCMParameterSpec
            GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, IV);
​
            // Initialize Cipher for DECRYPT_MODE
            cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);
​
            // Perform Decryption
            byte[] decryptedText = cipher.doFinal(cipherText);
​
            return new String(decryptedText);
        }
    }

我的Node.js代码

代码语言:javascript
复制
const crypto = require('crypto');
// input created by running above program in java
const ed = 'OGtANbvTLY6Cme2VNAxsiIhBLLwl29oVX7zC5DGmmq4hU/VqNKaGQuSp1Q8liQ94cW/B96OJoJJ2r67jRlQFI4qHCTWFU2qQ8QaNj6WehdVLsf5mDK2aMYjc/vXd1ha/cElMBzFaIp9g==='
const key = 'HuzPEZgzqKOo8VwlnYhNUaPWTWSVDRQ2bMtY6aJAp8I'
const iv = 'kg5ILA0826hrew5w'
const tag = 'jc/vXd1ha/cElMBzFaIp9g==' // last 16 bytes extracted in java

function decrypt(encrypted, ik, iiv, it) {
  let bData = Buffer.from(encrypted, 'base64');
  // console.log(bData.length,bData.length - 64)
  let tag1 = Buffer.from(tag, 'base64');
  // let tag1 = bData.slice((bData.length - 16),bData.length) // also tried slicing last 16 bytes of buffer
  console.log('00000000',tag1.length)
  let iv1 = Buffer.from(iiv, 'base64');
  let key1 = new Buffer(ik, 'base64');
  console.log('aaaaaaaaa')
  let decipher = crypto.createDecipheriv('aes-256-gcm', key1, iv1)
  console.log('bbbbbbbbbbbbb')
  decipher.setAuthTag(tag1);
  console.log('ccccccc')
  let dec = decipher.update(encrypted, 'binary', 'utf8')
  dec += decipher.final('utf8');
  return dec;
}

console.log('devryptedddddd',decrypt(ed,key,iv,tag))

我应该在node.js的控制台中得到“这是一个需要用Java 256 GCM加密算法加密的纯文本”,但我得到的是“不支持的状态或无法验证数据”错误。帮帮忙吧。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-27 11:42:06

您使用的“ed”不是该纯文本、键和IV的Java代码的输出。

代码语言:javascript
复制
OGtANbvTLY6Cme2VNAxsiIhBLLwl29oVX7zC5DGmmq4hU/VqNKaGQuSp1Q8liQ94cW/B96OJoJJ2r67jRlQFI4qHCTWFU2qQ8QaNj6WehdVLsf5mDK2aMY3P713dYWv3BJTAcxWiKfY=

(后22个字符不同)。但是这个值不是nodejs中使用的正确值;Java crypto返回GCM标记作为密码文本的最后N个字节,并且您正确地将它从那里复制到一个单独的变量,但是没有从密文中删除它。要在nodejs中使用的正确密文是在base64中:

代码语言:javascript
复制
OGtANbvTLY6Cme2VNAxsiIhBLLwl29oVX7zC5DGmmq4hU/VqNKaGQuSp1Q8liQ94cW/B96OJoJJ2r67jRlQFI4qHCTWFU2qQ8QaNj6WehdVLsf5mDK2aMQ==

(20字符较短,最后3字符不同)。

最后,nodejs执行bData = Buffer.from(encrypted, 'base64'),但随后忽略bData并执行decipher.update(encrypted, 'binary', 'utf8') --使用base64字符串作为二进制,但它不是。

代码语言:javascript
复制
const crypto = require('crypto');

const ed = 'OGtANbvTLY6Cme2VNAxsiIhBLLwl29oVX7zC5DGmmq4hU/VqNKaGQuSp1Q8liQ94cW/B96OJoJJ2r67jRlQFI4qHCTWFU2qQ8QaNj6WehdVLsf5mDK2aMQ=='
const key = 'HuzPEZgzqKOo8VwlnYhNUaPWTWSVDRQ2bMtY6aJAp8I'
const iv = 'kg5ILA0826hrew5w'
const tag = 'jc/vXd1ha/cElMBzFaIp9g==' // last 16 bytes extracted in java

function decrypt(encrypted, ik, iiv, it) {
  let bData = Buffer.from(encrypted, 'base64');
  let tag1 = Buffer.from(tag, 'base64');
  let iv1 = Buffer.from(iiv, 'base64');
  let key1 = new Buffer(ik, 'base64');
  let decipher = crypto.createDecipheriv('aes-256-gcm', key1, iv1)
  decipher.setAuthTag(tag1);
  let dec = decipher.update(bData, 'utf8')
  dec += decipher.final('utf8');
  return dec;
}
console.log(decrypt(ed,key,iv,tag))

我得到了正确的输出,但也警告new Buffer() (用于key1)是不推荐的;现在首选Buffer.from作为其他变量。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58130325

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档