本文介绍了如何在CBC模式和PKCS7填充中解码使用AES-256加密的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用下面的Java代码解密在CBC模式和PKCS7填充下使用AES-256加密的数据.

We are using below java code to decrypt the data which is encrypted using AES-256 in CBC mode and PKCS7 padding.

Java代码:

import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import java.security.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;


public class AES256 {

    private static byte[] initVector = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

    public String decrypt (String encryptedDataBase64, String keyBase64)
    {
       try {
           Security.setProperty("crypto.policy", "unlimited");
           IvParameterSpec ivSpec = new IvParameterSpec(initVector);  // Get the init vector

           // Get the Base64-encoded key
           byte[] key = Base64.decodeBase64(keyBase64.getBytes("UTF-8"));
           Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");  // AES / CBC / PKCS5 padding
           SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
           cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
           byte[] encryptedData = Base64.decodeBase64(encryptedDataBase64.getBytes("UTF-8"));
           byte[] decryptedData = cipher.doFinal(encryptedData);

           return new String(decryptedData);
       }
       catch (Exception e) {
           logger.error("AES256 Decrypt: Decryption exception: "+ e.getMessage());
           return null;
       }
    }
}

现在,我们需要将解密逻辑转换为Javascript,因为我们的应用程序正在发送标头中的加密数据,同时从服务器请求index.html.我尝试使用Crypto.js解密,但解码的字符串为空.以下是我尝试使用的Javascript代码.

Now we need to convert this decryption logic to Javascript as our app is sending the encrypted data in the headers while requesting for index.html from server. I tried to decrypt using Crypto.js but I am getting decoded string as empty. Below is the Javascript code I was trying to use.

var key = CryptoJS.enc.Base64.parse(keyBase64);
var data = CryptoJS.enc.Base64.parse(encryptedDataBase64);
var dec_data = CryptoJS.AES.decrypt(data, key);

dec_data空着.

dec_data is coming as empty.

在阅读了一些关于栈溢出的问题后,我尝试了这个方法.任何人都可以让我知道代码中是否有错误.

I tried this after reading some of stack over flow questions. Can any one please let me know if there is any error in the code.

推荐答案

不幸的是,您没有提供任何示例数据来测试您的环境,因此我设置了自己的值.使用此值:

Unfortunately you didn't provide any sample data to test with your environment so I setup my own values. Using this values:

ciphertext = rjygE0TjIqiQ4ETnpszoieRWzaSD+9oINf1c748VcL/3zD5AazSFomx4paeanihz
keyBase64 = MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=
ivBase =  AAAAAAAAAAAAAAAAAAAAAA==

我在Java上得到了这个解密结果:

I'm getting this decrypt-result on Java:

The quick brown fox jumps over the lazy dog

在Javascript端,我的代码收到了相同的结果:

On Javascript-side I receive the same results with my code:

decrypted (str): The quick brown fox jumps over the lazy dog

可以在此处进行实时测试-Java: https://paiza.io/projects/e/dHG73CRgJojOOfLxtvJjtg 和Javascript: https://playcode.io/672463 .

A live test can be done here - Java: https://paiza.io/projects/e/dHG73CRgJojOOfLxtvJjtg and Javascript: https://playcode.io/672463.

请注意,我的代码没有异常处理,仅用于教育目的.此外,您的代码是不安全的,因为它使用了静态(固定)密钥和初始化向量.

Java代码(由于我使用的是Base64编码器中内置的Java 11,因此略有更改):

Java code (slightly changed as I'm using the Java 11 built in Base64 encoder):

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Base64;

public class Main {

    private static byte[] initVector = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println("How to decode data encrypted using AES-256 in CBC mode and PKCS7 padding");
        String plaintext = "The quick brown fox jumps over the lazy dog";
        byte[] key = "12345678901234567890123456789012".getBytes("UTF-8");
        String keyBase64 = Base64.getEncoder().encodeToString(key);
        System.out.println("keyBase64: " + keyBase64);
        String ivBase64 = Base64.getEncoder().encodeToString(initVector);
        System.out.println("initVector: " + ivBase64);
        String ciphertext = "rjygE0TjIqiQ4ETnpszoieRWzaSD+9oINf1c748VcL/3zD5AazSFomx4paeanihz";
        System.out.println("ciphertext: " + ciphertext);
        String decryptedtext = decrypt(ciphertext, Base64.getEncoder().encodeToString(key));
        System.out.println("decryptedtext: " + decryptedtext);
    }

    public static String decrypt (String encryptedDataBase64, String keyBase64)
    {
        try {
            Security.setProperty("crypto.policy", "unlimited");
            IvParameterSpec ivSpec = new IvParameterSpec(initVector);  // Get the init vector
            // Get the Base64-encoded key
            byte[] key = Base64.getDecoder().decode(keyBase64.getBytes("UTF-8"));
            //byte[] key = Base64.decodeBase64(keyBase64.getBytes("UTF-8"));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");  // AES / CBC / PKCS5 padding
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
            byte[] encryptedData = Base64.getDecoder().decode(encryptedDataBase64.getBytes("UTF-8"));
            //byte[] encryptedData = Base64.decodeBase64(encryptedDataBase64.getBytes("UTF-8"));
            byte[] decryptedData = cipher.doFinal(encryptedData);
            return new String(decryptedData);
        }
        catch (Exception e) {
            System.out.println("AES256 Decrypt: Decryption exception: "+ e.getMessage());
            //logger.error("AES256 Decrypt: Decryption exception: "+ e.getMessage());
            return null;
        }
    }
}

JavaScript代码:

Javascript code:

let keyBase64 = 'MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=';
let ivBase64 = 'AAAAAAAAAAAAAAAAAAAAAA==';
let iv = CryptoJS.enc.Base64.parse(ivBase64);
let secret_key = CryptoJS.enc.Base64.parse(keyBase64);
ciphertext = 'rjygE0TjIqiQ4ETnpszoieRWzaSD+9oINf1c748VcL/3zD5AazSFomx4paeanihz';
console.log('ciphertext: ', ciphertext);
var decrypted = CryptoJS.AES.decrypt(ciphertext, secret_key,{
  iv: iv,
  padding: CryptoJS.pad.Pkcs7,
  mode: CryptoJS.mode.CBC,
});
console.log('decrypted (str): ', CryptoJS.enc.Utf8.stringify(decrypted).toString());

这篇关于如何在CBC模式和PKCS7填充中解码使用AES-256加密的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 09:22