Quantcast
Channel: AEM Guide
Viewing all articles
Browse latest Browse all 162

Encrypting and Decrypting String in Java

$
0
0
The Advanced Encryption Standard (AES), also known by its original name Rijndael (Dutch pronunciation: [ˈrɛindaːl]),[5][6] is a specification for the encryption of electronic data established by the U.S. National Institute of Standards and Technology (NIST) in 2001.[7]

Below is sample java code to encrypt and decrypt a string.


packagecom.kishore;

importjava.io.UnsupportedEncodingException;
importjava.security.MessageDigest;
importjava.security.NoSuchAlgorithmException;
importjava.util.Arrays;

importjavax.crypto.Cipher;
importjavax.crypto.spec.SecretKeySpec;

importorg.apache.commons.codec.binary.Base64;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;

publicclassEncrypt {

protectedfinalLoggerLOGGER=LoggerFactory.getLogger(this.getClass());

publicstaticvoidmain(String[] args) {
String encryptString ="45634634";
finalStringKEY="kishore";
Encrypt obj =newEncrypt();
String encryptedString = obj.encrypt(encryptString, obj.encryptSecretKey(KEY));
System.out.println("encryptedString: "+encryptedString);
String decyptedString = obj.decrypt(encryptedString, obj.encryptSecretKey(KEY));
System.out.println("decyptedString: "+decyptedString);
}
publicSecretKeySpecencryptSecretKey(finalStringsecretKey) {
MessageDigest sha =null;
SecretKeySpec encryptApiSecret =null;
try {
byte[] key = secretKey.getBytes("UTF-8");
sha =MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key =Arrays.copyOf(key, 16);
encryptApiSecret =newSecretKeySpec(key, "AES");
} catch (finalNoSuchAlgorithmException e) {
LOGGER.error("Exception occurred in encryptApiSecret",e);
} catch (finalUnsupportedEncodingException e) {
LOGGER.error("Exception occurred in encryptApiSecret",e);
}
return encryptApiSecret;
}

publicStringdecrypt(finalStringstrToDecrypt, finalSecretKeySpecsecretKey) {
String decryptedApiKey ="";
try {
finalCipher cipher =Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] c =Base64.decodeBase64(strToDecrypt.getBytes("UTF-8"));
decryptedApiKey =newString(cipher.doFinal(c));
} catch (finalException e) {
LOGGER.error("Exception occurred in decrypt",e);
}
return decryptedApiKey;
}

publicStringencrypt(finalStringstrToDecrypt, finalSecretKeySpecsecretKey) {
String encryptedApiKey ="";
try {
finalCipher cipher =Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] c = cipher.doFinal(strToDecrypt.getBytes());
encryptedApiKey =newString(Base64.encodeBase64(c));
} catch (finalException e) {
LOGGER.error("Exception occurred in encrypt",e);
}
return encryptedApiKey;
}

}



Viewing all articles
Browse latest Browse all 162

Trending Articles