Skip to content

Instantly share code, notes, and snippets.

@ashee
Created November 19, 2016 00:05
Show Gist options
  • Save ashee/5bcda2ecdf67bae953c821818ed3b31a to your computer and use it in GitHub Desktop.
Save ashee/5bcda2ecdf67bae953c821818ed3b31a to your computer and use it in GitHub Desktop.
Password Based Encryption
import java.security.*
import javax.crypto.*
import javax.crypto.spec.*
import javax.xml.bind.DatatypeConverter
class PBE {
def secretKey;
def salt = getSalt();
def iterations = 65536 ;
def keySize = 256;
def ivBytes;
def saltBytes = getSalt()
def getSalt() {
def salt = new byte[20]
SecureRandom.getInstance("SHA1PRNG").nextBytes(salt)
return new String(salt);
}
def encrypt(char[] plaintext) {
byte[] saltBytes = salt.getBytes();
// def skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
def skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512"); // only in java 8, uncomment above for java 7
def spec = new PBEKeySpec(plaintext, saltBytes, iterations, keySize);
secretKey = skf.generateSecret(spec);
def secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretSpec);
def params = cipher.getParameters();
ivBytes = params.getParameterSpec(IvParameterSpec).getIV();
byte[] encryptedTextBytes = cipher.doFinal(String.valueOf(plaintext).getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(encryptedTextBytes);
}
def decrypt(char[] encryptedText) {
def encryptedTextBytes = DatatypeConverter.parseBase64Binary(new String(encryptedText));
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretSpec, new IvParameterSpec(ivBytes));
def decryptedTextBytes = null;
try {
decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return new String(decryptedTextBytes);
}
}
def pbe = new PBE()
def message = "PasswordToEncrypt".toCharArray();
def cipher = pbe.encrypt(message)
def plaintext = pbe.decrypt(cipher.toCharArray())
println("Message: " + String.valueOf(message));
println("Encrypted: " + cipher);
println("Decrypted: " + plaintext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment