1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| import com.google.common.base.Charsets;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@Component
public class CipherUtilTopSecret {
private final Logger log = LoggerFactory.getLogger(CipherUtilTopSecret.class);
public static final String CIPHER_ALGORITHM = "AES";
public static final String KEY_ALGORITHM = "AES";
public static final String PASS_HASH_ALGORITHM = "SHA-256";
public static final String DEFAULT_PASS = "Your Default Security PassPhrase";
public String encrypt(String data) {
try {
Cipher cipher = buildCipher(DEFAULT_PASS, Cipher.ENCRYPT_MODE);
byte[] dataToSend = data.getBytes(Charsets.UTF_8);
byte[] encryptedData = cipher.doFinal(dataToSend);
return Base64.encodeBase64URLSafeString(encryptedData);
} catch (Exception e) {
log.warn(e.getMessage(), e);
throw new RuntimeException(e);
}
}
public String decrypt(String encryptedValue) {
try {
Cipher cipher = buildCipher(DEFAULT_PASS, Cipher.DECRYPT_MODE);
byte[] encryptedData = Base64.decodeBase64(encryptedValue);
byte[] data = cipher.doFinal(encryptedData);
return new String(data, Charsets.UTF_8);
} catch (Exception e) {
log.warn(e.getMessage(), e);
throw new RuntimeException(e);
}
}
private Cipher buildCipher(String password, int mode) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
Key key = buildKey(password);
cipher.init(mode, key);
return cipher;
}
private Key buildKey(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest digester = MessageDigest.getInstance(PASS_HASH_ALGORITHM);
digester.update(String.valueOf(password).getBytes(Charsets.UTF_8.name()));
byte[] key = digester.digest();
return new SecretKeySpec(key, KEY_ALGORITHM);
}
public static void main(String[] args) {
CipherUtilTopSecret cipherUtil = new CipherUtilTopSecret();
// Encryption
String encryptedString = cipherUtil.encrypt("4,5,6 cueillir des cerises : " + String.valueOf(new Date().getTime()));
// Before Decryption
System.out.println("Avant decrypt : " + encryptedString);
String s = cipherUtil.decrypt(encryptedString);
System.out.println("Après decrypt : " + s);
}
} |
Partager