[英]How to Encrypt data to a Plain text without Special character in java
我需要一种加密算法,我可以将数据加密成简单的纯文本。
目前我正在使用AES 加密算法转换为加密字符串包含特殊字符。
这里如果我通过url中的查询字符串发送此字符串,我会遗漏一些像“+”这样的字符。
所以我需要一个安全的加密逻辑,只包含字母表。
这是我的加密逻辑:
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;
}
@SuppressWarnings("restriction")
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;
}
这里我得到一个加密的字符串“ TEj + TWBQExpz8 / p5SAjIhA == ”
而我通过查询字符串发送
本地主机:8080 / MyProject的/家用代码= TEJ + TWBQExpz8 / p5SAjIhA ==
我在控制器中得到字符串 -
“ TEj TWBQExpz8 / p5SAjIhA == ”
“+”符号丢失,这就是为什么我在解密时遇到问题。
请建议任何新的算法或任何解决方案,以避免特殊字符。
谢谢。
您可以使用URLEncoder对加密部分进行编码
URLEncoder.encode("TEj+TWBQExpz8/p5SAjIhA==", "UTF-8")
使其对URL有效。
http://docs.oracle.com/javase/8/docs/api/java/net/URLEncoder.html
在通过URL发送之前,必须使用URLEncoder
对加密值进行编码。
在解密方面,您必须首先使用URLDecoder
来解码接收的数据。
您可以在代码中执行以下操作来实现此目的:
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);
String urlEncodeddata=URLEncoder.encode(encryptedValue,"UTF-8");
return urlEncodeddata;
}
@SuppressWarnings("restriction")
public static String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
String urlDecodedData=URLDecoder.decode(encryptedData, "UTF-8");
byte[] decordedValue = new BASE64Decoder().decodeBuffer(urlDecodedData);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
仅使用URLEncode
无需更改代码。
String encodedStr = URLEncoder.encode(encrypt("XYZ"), "UTF-8");
并且不需要使用URLDecode来解码url,因为你可以使用普通的decrypt(encodedStr);
在通过URL发送之前,您必须在C#Application中使用它来对加密值进行编码。 解密方面,你必须首先使用UrlDecode来解码QueryString数据。
Server.UrlEncode("");
Server.UrlDecode("");
我在基于Spring的应用程序中遇到了同样的问题,我用Base64编码/解码过程解决了这个问题。
编码方式:
String encryptedString = encrypt(stringData);
byte[] encoded = Base64.getEncoder().encode(encryptedString.getBytes(StandardCharsets.UTF_8));
String base64Encoded = new String(encoded);
解码:
byte[] decoded = Base64.getDecoder().decode(base64Encoded.getBytes(StandardCharsets.UTF_8));
String encryptedString = new String(decoded);
您可以在解密方法上成功解密“encryptedString”值。
String decryptedString = decrypt(encryptedString);
我希望它有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.