AES加密的不同行为

问题描述

我有以下代码,这很简单,但是,在Spring Tool Suite和Command Prompt中运行时,这些代码会导致不同的结果。两种环境中的JDK版本都相同。我也尝试过使用Java 8和11,但是有相同的症状。对我还要看的东西有什么见识?对我来说这是一个奇怪的情况。任何帮助都将受到高度赞赏。

public class CryptoUtil
{
    public final static Charset ENCODING = StandardCharsets.UTF_8;
    public final static String ALGO_AND_ParaMS = "AES/CBC/PKCS5PADDING";
    public final static String ENCR_ALGO = "AES";
    public final static String HASH_ALGO = "PBKDF2WithHmacSHA256";
    public final static int KEYGEN_IteraTIONS = 65536  ;
    public final static int KEYGEN_KEY_SIZE = 256;
    public final static String KEYGEN_SALT = "w4sh3Vzp2ZX6GmPC";
    public final static String KEYGEN_IV = "2QZv3t6OOCLIf6vG";
    
    public static String decrypt(String cyphertext,String password)
        throws Exception
    {

        String plaintext;

        try {

            IvParameterSpec ivspec = new IvParameterSpec(KEYGEN_IV.getBytes(ENCODING));

            SecretKeyFactory factory = SecretKeyFactory.getInstance(HASH_ALGO);
            KeySpec spec = new PBEKeySpec(password.tochararray(),KEYGEN_SALT.getBytes(ENCODING),KEYGEN_IteraTIONS,KEYGEN_KEY_SIZE);
            SecretKey tmp = factory.generateSecret(spec);
            SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(),ENCR_ALGO);

            Cipher cipher = Cipher.getInstance(ALGO_AND_ParaMS);
            cipher.init(Cipher.DECRYPT_MODE,secretKey,ivspec);
            plaintext = new String(cipher.doFinal(Base64.getDecoder().decode(cyphertext)));

        } catch (Exception e) {
            throw new Exception("Error while decrypting " + cyphertext,e);
        }

        return plaintext;
    }

    public static String encrypt(String plaintext,String password)
            throws Exception
    {
        String cyphertext;

        try {

            IvParameterSpec ivspec = new IvParameterSpec(KEYGEN_IV.getBytes(ENCODING));

            SecretKeyFactory factory = SecretKeyFactory.getInstance(HASH_ALGO);
            KeySpec spec = new PBEKeySpec(password.tochararray(),ENCR_ALGO);

            Cipher cipher = Cipher.getInstance(ALGO_AND_ParaMS);
            cipher.init(Cipher.ENCRYPT_MODE,ivspec);
            cyphertext = new String(Base64.getEncoder().encode(cipher.doFinal(plaintext.getBytes(ENCODING))));

        } catch (Exception e) {
            throw new Exception("Error while encrypting " + plaintext,e);
        }

        return cyphertext;
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)