首页 > 解决方案 > 为什么以下 AES 加密和解密在主要方法中有效,但在客户端服务器上无效?

问题描述

不仅上述加密字符串无法从客户端解密。而且,它无法在以下网站中解密。 https://www.devglan.com/online-tools/aes-encryption-decryption

我在上述网站上尝试解密时遇到的错误是

错误:给定最终块未正确填充。如果在解密期间使用了错误的密钥,则可能会出现此类问题。

PS:出于测试目的,我将密钥设置为静态。

package com.snapwork.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
 
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.sun.mail.util.ASCIIUtility;

import javax.crypto.spec.IvParameterSpec;
 
public class AES {
 
    private static SecretKeySpec secretKey;
    private static byte[] key ;
    private static byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    private static IvParameterSpec ivspec;
    

 
public static void setKeyAndIV(String myKey) 
{
    MessageDigest sha = null;
    ivspec = new IvParameterSpec("39d0a599ea7c1761".getBytes());
   
    try {
        key = myKey.getBytes("UTF-8");
        sha = MessageDigest.getInstance("SHA-256");
        key = sha.digest(key);
        secretKey = new SecretKeySpec(key, "AES");
    } 
    catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } 
    catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

public static String encrypt(String strToEncrypt, String secret) 
{
    try
    {
        setKeyAndIV(secret);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
        return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
    } 
    catch (Exception e) 
    {
        System.out.println("Error while encrypting: " + e.toString());
    }
    return null;
}

public static String decrypt(String strToDecrypt, String secret) 
{
    try
    {
        setKeyAndIV(secret);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
        return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
    } 
    catch (Exception e) 
    {
        System.out.println("Error while decrypting: " + e.toString());
    }
    return null;
}

public static void main(String[] args) 
{
    final String myKey = "8e990516e545ba4103dcb32a3462c54b";
    
    String fullName = "ANURAG"; String mobileNumber = "9930858174"; String
      emailId = "xyz@gmail.com"; String custIdentifier = "4127672700000765";
      String availableCredits = "9815646465"; String eligibleOfferTag = "94913";
     
     
     
    String inputString = fullName + "|" + mobileNumber + "|" + emailId + "|" + custIdentifier + "|" + availableCredits + "|" + eligibleOfferTag;
    String decryptedString = AES.encrypt(inputString, myKey) ;
     
    System.out.println(decryptedString);
}

}

标签: javaaes

解决方案


我刚刚评论了这一行key = sha.digest(key);,它开始工作了。问题可能是客户端没有使用该行。那条线可能正在修改静态密钥,所以我无法在 devglan 网站上解密

无论如何,谢谢大家的建议。


推荐阅读