java - Commons Codec 中 decodeBuffer 方法的合适替代品

标签 java encryption base64 aes apache-commons

我有一段使用 sun.misc.* 包使用 AES 算法加密和解密的代码。

后来我才知道使用这些包是错误的,这让我遵循了使用 Apache 的 Commons Codec 的建议,这是有效的。

之前的代码如下:

import java.security.*;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;


import sun.misc.*;

public class AESencrp {
private static final String ALGO = "AES";
private static final byte[] keyValue = 
    new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't','S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };

public static String encrypt(String Data) throws Exception {
    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.ENCRYPT_MODE, key);
    byte[] encVal = c.doFinal(Data.getBytes());
    String encryptedValue = new BASE64Encoder().encode(encVal);
    return encryptedValue;
}

public static String decrypt(String encryptedData) throws Exception {
    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.DECRYPT_MODE, key);
    byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
    byte[] decValue = c.doFinal(decordedValue);
    String decryptedValue = new String(decValue);
    return decryptedValue;
}

private static Key generateKey() throws Exception {
    Key key = new SecretKeySpec(keyValue, ALGO);
    return key;
}



}

按照建议,我删除了 sun.misc 并进行了以下更改。

在 Apache 的通用编解码器中用 Base64 替换 BASE64Encoder 类后:

 public static String encrypt(String Data) throws Exception {
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGO);
            c.init(Cipher.ENCRYPT_MODE, key);
            byte[] encVal = c.doFinal(Data.getBytes());
            byte[] encryptedValue = new Base64().encode(encVal);
            return new String(encryptedValue);
        }

我找不到合适的解密替代品,因为我被击中了:

byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);

我没有找到任何方法来完成 decodeBuffer(String encryptedData) 的工作并返回 decodedValue 的字节数组。

最佳答案

好的,那这个呢?

使用 apache Base64 util 类类似于 sun.misc.Base64Encoder。 Apache Base64 类提供了许多重载方法,可以减轻字节和字符串之间的转换。

byte[] encodedBytes  = Base64.encodeBase64(testString.getBytes());

String decodedString = new String(Base64.decodeBase64(encodedBytes));

关于java - Commons Codec 中 decodeBuffer 方法的合适替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13599267/

相关文章:

c# - 将图像从 Windows Phone 应用程序发布到 PHP

java - Spring 安全 : 404 on logout

java - 如何使用 MessageDigest , Base64 解码

image - Meteor:上传图片并作为base64字符串保存到数据库

sockets - 为套接字连接实现握手

java - 是什么导致错误 "java.security.InvalidKeyException: Parameters missing"?

encryption - 如何在 Openssl 中以十六进制生成输出?

java - 是什么让 String 不可变?

一般递归自类型值的 Java 字段类型?

java - 在java中分割字符串的正则表达式