gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:02:28 25 4
gpt4 key购买 nike

我有一段使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com