Encrypt/Decrypt with salt
This is an example of how to encrypt and decrypt using a salt. The salt is random data very often used in cryptography as additional input to a hash function. Doing encryption and decryption of a String with a salt implies that you should:
- Read an initial String.
- Generate random bytes to be placed in the salt.
- Create a
sun.misc.BASE64Decoder(a Utility Class to encode a String or ByteArray as a Base64 encoded String) and a byte array to be used as a salt. - Use the
BASE64Encoderto encode both the salt and the String and return them, as described in theencrypt(String str)method. - Read the encrypted String.
- Create a
sun.misc.BASE64Encoder(A utility class to decode a Base64 encoded String to a ByteArray) to decode the String to a byte array. - Return the String representation of the byte array, as shown in the
decrypt(String encstr)method.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;import java.io.IOException;import java.util.Date;import java.util.Random;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;public class Main { private static Random rand = new Random((new Date()).getTime()); public static void main(String[] args) throws Exception { String st = "secrete"; String enc = encrypt(st); System.out.println("Encrypted string :" + enc); System.out.println("Decrypted string :" + decrypt(enc)); } public static String encrypt(String str) { BASE64Encoder encoder = new BASE64Encoder(); byte[] salt = new byte[8]; rand.nextBytes(salt); return encoder.encode(salt) + encoder.encode(str.getBytes()); } public static String decrypt(String encstr) { if (encstr.length() > 12) {String cipher = encstr.substring(12);BASE64Decoder decoder = new BASE64Decoder();try { return new String(decoder.decodeBuffer(cipher));} catch (IOException e) { // throw new InvalidImplementationException( //Fail} } return null; }}Output:
Encrypted string :CT6/c+0AAmU=c2VjcmV0ZQ== Decrypted string :secrete
This was an example of how to encrypt and decrypt using a salt in Java.

Thank you!
We will contact you soon.



