gpt4 book ai didi

java - 从 AES 加密字符串中删除\r 和\n

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:04:55 25 4
gpt4 key购买 nike

我正在使用 AES 加密字符串,但加密后的字符串末尾包含 \n\r

 public class AESImpl {

private static String decryptedString;

private static String encryptedString;

public static void main(String[] args) throws NoSuchAlgorithmException, IOException, ClassNotFoundException {

String strToEncrypt = "This text has to be encrypted";
SecretKey secretKey = generateSecretKey();
String encryptStr = encrypt(strToEncrypt, secretKey);
System.out.println("Encrypted String : " + encryptStr + "It should not come in new line");
String decryptStr = decrypt(encryptStr, secretKey);
System.out.println("Decrypted String : " + decryptStr);
}

private static SecretKey generateSecretKey() throws NoSuchAlgorithmException, IOException {
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128);
SecretKey sk = kg.generateKey();
String secretKey = String.valueOf(Hex.encodeHex(sk.getEncoded()));
System.out.println("Secret key is " + secretKey);
return sk;
}

public static String encrypt(String strToEncrypt, SecretKey secretKey) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
encryptedString = new String(Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes())));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}

return encryptedString;
}

public static String decrypt(String strToDecrypt, SecretKey secretKey) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
decryptedString = new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt)));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}

return decryptedString;
}
}

输出

Secret key is 2df36561b09370637d35b4a310617e60
Encrypted String : TUDUORnWtsZFJAhBw1fYMF9CFExb/tSsLeDx++cpupI=
It should not come in new line
Decrypted String : This text has to be encrypted

实际上,加密后的字符串是TUDUORnWtsZFJAhBw1fYMF9CFExb/tSsLeDx++cpupI=/r/n。我是否需要显式替换加密字符串中的 \r\n 或者我在上面的代码中做错了什么?

最佳答案

添加Base64.encodeBase64String(hashPassword,Base64.NO_WRAP) 删除\n。

默认情况下,它使用添加换行符的 Base64.DEFAULT

点击此处:source

点击此处:Main source

关于java - 从 AES 加密字符串中删除\r 和\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21852889/

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