Many times, when we generate an encrypted string, the resulted output string is filled with all sorts of special characters. While this encrypted string is usually fine and safe for database storage, but it’s a big problem in some instances - such as XML file, or when it’s needed to be transmitted as HTTP GET request.
In this case, we can apply Base64 on the encrypted string, convert it to an US-ASCII character string. Following is an example of code snippet. Please note that, the Encryption class is just a dummy example to simplify this example. You may use the Java Cryptography Architecture (JCA) Cipher class to achieve reversible encryption.
String encryptedString = Encryption.encrypt("StringToBeEncrypted", "key");
String base64Encoded = Base64.encode(encryptedString.getBytes());
System.out.println("Encoded: " + base64Encoded);
byte[] base64Decoded = Base64.decode(base64Encoded);
String descryptedString = Encryption.decrypt(new String(base64Decoded), "key");
System.out.println("Decrypted: " + descryptedString);
In the above example, I’m using com.sun.org.apache.xerces.internal.impl.dv.util.Base64 (found in rt.jar of Java5 and above) to apply Base64 encoding. You may also use org.apache.commons.codec.binary.Base64 found in Apache Commons Codec to achieve the same result.
Related Posts:













0 Responses to “Java: How to Generate Encrypted String without Any Special Character”