Skip to content

Instantly share code, notes, and snippets.

@aphexmunky
Created October 26, 2012 14:11
Show Gist options
  • Save aphexmunky/3959031 to your computer and use it in GitHub Desktop.
Save aphexmunky/3959031 to your computer and use it in GitHub Desktop.
Encryption Bean
package com.thehutgroup.thirdpartyplatform.service;
public interface SymmetricEncryption {
public String encrypt(String plainText, String salt);
public String encrypt(String plainText, int salt);
public String decrypt(String encryptedText, String salt);
public String decrypt(String encryptedText, int salt);
}
package com.thehutgroup.thirdpartyplatform.service.impl;
import java.security.Key;
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.thehutgroup.thirdpartyplatform.service.SymmetricEncryption;
@Component
public class SymmetricEncryptionImpl implements SymmetricEncryption {
@Value("${encryption.key}")
String encryptionKey;
private static final String ALG = "AES";
@Override
public String encrypt(String plainText, String salt) {
try {
Key key = generateKey(salt);
Cipher c = Cipher.getInstance(ALG);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = c.doFinal(plainText.getBytes());
String b64encrypted = DatatypeConverter.printBase64Binary(encrypted);
return b64encrypted;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public String decrypt(String encryptedText, String salt) {
try {
Key key = generateKey(salt);
Cipher c = Cipher.getInstance(ALG);
c.init(Cipher.DECRYPT_MODE, key);
byte[] b64encrypted = DatatypeConverter.parseBase64Binary(encryptedText);
byte[] unencrypted = c.doFinal(b64encrypted);
String saltedPlaintext = new String(unencrypted);
return saltedPlaintext;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private Key generateKey(String salt) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] hash = md.digest((encryptionKey + salt).getBytes("UTF-8"));
byte[] key = Arrays.copyOf(hash, 16);
return new SecretKeySpec(key, ALG);
}
@Override
public String encrypt(String plainText, int salt) {
return encrypt(plainText, Integer.toString(salt));
}
@Override
public String decrypt(String encryptedText, int salt) {
return decrypt(encryptedText, Integer.toString(salt));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment