在Commons Codec中合适地替代encodeBuffer方法

bal*_*208 1 java encryption base64 aes apache-commons

我有一段代码使用AES算法进行加密和解密,该算法使用sun.misc。*软件包。

后来我才知道,使用那些使我听从使用有效的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;
}



}
Run Code Online (Sandbox Code Playgroud)

按照建议,我删除了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);
        }
Run Code Online (Sandbox Code Playgroud)

我无法找到合适的解密替代品,因为我在网上被撞到了:

byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
Run Code Online (Sandbox Code Playgroud)

我没有找到任何可以做的解码缓冲区(字符串encryptedData)的工作,并返回给我一个字节数组的decodedValue的方法。

Har*_*Raj 5

好,那呢?

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

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

String decodedString = new String(Base64.decodeBase64(encodedBytes));
Run Code Online (Sandbox Code Playgroud)