当前位置: 首页 > 知识库问答 >
问题:

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

步胜
2023-03-14
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);
        }
    }
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))

共有1个答案

刁丰羽
2023-03-14

您使用的“ed”不是Java代码对明文、键和IV的输出。我得到的值在base64中

OGtANbvTLY6Cme2VNAxsiIhBLLwl29oVX7zC5DGmmq4hU/VqNKaGQuSp1Q8liQ94cW/B96OJoJJ2r67jRlQFI4qHCTWFU2qQ8QaNj6WehdVLsf5mDK2aMY3P713dYWv3BJTAcxWiKfY=

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

OGtANbvTLY6Cme2VNAxsiIhBLLwl29oVX7zC5DGmmq4hU/VqNKaGQuSp1Q8liQ94cW/B96OJoJJ2r67jRlQFI4qHCTWFU2qQ8QaNj6WehdVLsf5mDK2aMQ==

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

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))
 类似资料:
  • 节点模块: Java类:主要方法现在只是用于测试,稍后将被删除。

  • 我已经使用OpenSSL AES-256-GCM加密了一个文件。由于aes-256-gcm不受命令行支持,我已经安装了LibreSSL,我可以使用下面的命令加密文件的数据。 openssl ENC-AES-256-GCM-K 616161616161616161616161616161616161616161616161616161616161616161-IV 768A5C31A97D5FE9-

  • 我试图创建一个应用程序在NodeJS(电子)作为一个跨平台桌面应用程序。这将与iOS上使用SWIFT开发的移动应用程序配对。作为共享数据的一部分,它使用AES-256-GCM算法进行加密。我在SWIFT中有以下加密和解密方法: 对于NodeJS,我有以下函数: null 下面是Java代码: 数据:这是数据 密钥:密码 根据我所读到的,Java将生成包含AuthTag的加密文本。我尝试将AuthT

  • 这是一个错误: 1.JS

  • 我正在尝试将我的应用程序从128位AES密钥升级为256位AES。然而,当我将第54行从128更改为256时,我会得到以下密钥大小错误。 java.security.无效密钥异常: 非法的密钥大小 我已正确安装了JCE文件,我的应用程序生成较长的密钥这一事实证明了这一点。 我在其他文章中看到过“AES / CBC / PKCS7Padding”加密方法,但这只会让我遇到这个例外:

  • 1.我有java函数,它加密xml文件并返回加密的字符串。 2.我有c#函数,它可以解密由java函数加密的消息。 Java加密功能运行良好。但问题是C函数, 当我解密时,会得到下面的错误消息 我使用下面的参考搜索解决方案 Java中的AES加密和C#中的解密 C#/Java|AES256加密/解密 C#和Java中的加密/解密 但我仍然面临同样的错误。谁能给我提个建议吗。 我只是改变我的C#加密