很少有字符串无法使用Java中的AES256加密

时间:2019-02-12 16:41:50

标签: java encryption aes sha256

每当我尝试对应用程序中的单个字符字符串进行加密时,都会出现这种情况。当我尝试使用main方法加密相同的字符串时,便能够对其进行加密。但是,当我使用该应用程序运行时,此特定问题就要来了。我觉得这很奇怪,因为它正在使用main方法。

我的加密代码如下。

public static String encryptWithAES256(String strToEncrypt) throws Exception
{
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    byte[] encodedhash = digest.digest(KEY.getBytes(StandardCharsets.UTF_8));
    IvParameterSpec ivspec = new IvParameterSpec(Arrays.copyOf(KEY.getBytes(),16));
    SecretKeySpec secretKey = new SecretKeySpec(encodedhash, AES_ENCRYPTION_ALGORITHM);
    Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
    return new String(Base64.encodeBase64(cipher.doFinal(strToEncrypt.getBytes(CHARACTER_ENCODING))));
}

0 个答案:

没有答案