use*_*519 7 java encryption newline aes carriage-return
我使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
产量
Secret key is 2df36561b09370637d35b4a310617e60
Encrypted String : TUDUORnWtsZFJAhBw1fYMF9CFExb/tSsLeDx++cpupI=
It should not come in new line
Decrypted String : This text has to be encrypted
Run Code Online (Sandbox Code Playgroud)
实际上,加密的字符串是TUDUORnWtsZFJAhBw1fYMF9CFExb/tSsLeDx++cpupI=/r/n.我是否需要明确地替换加密字符串\r和\n从加密字符串中删除,或者我在上面的代码中做错了什么?
实际上,我使用 apache commons-codec-1.4.0.jar对字符串进行编码。将其更改为更高版本可以解决问题。encodeBase64String 方法的行为已从多行分块(commons-codec-1.4)更改为单行非分块(commons-codec-1.5)。
请点击链接了解更多详情。 http://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Base64.html