Example of encryption and decryption function of java based on AES symmetric encryption algorithm
- 2020-05-27 05:37:19
- OfStack
This paper illustrates the encryption and decryption functions of java based on AES symmetric encryption algorithm. I will share it with you for your reference as follows:
package com.soufun.com;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* @author WHD
*/
public class AesUtil {
private static final String AES="AES";
private static final String UTF8="UTF-8";
static KeyGenerator kgen =null;
static{
try {
kgen= KeyGenerator.getInstance(AES);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* @param content:
* @param password:
*/
private static byte[] encrypt(String content, String password) {
try {
// Use static code blocks to generate KeyGenerator object
//KeyGenerator kgen = KeyGenerator.getInstance(AES);
// use 128 position
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] encodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(encodeFormat, AES);
// Cipher The object actually does the encryption
Cipher cipher = Cipher.getInstance(AES);
// Encrypted content is encoded
byte[] byteContent = content.getBytes(UTF8);
// Initialize with a key Cipher object
cipher.init(Cipher.ENCRYPT_MODE, key);
// Formally perform the encryption operation
byte[] result = cipher.doFinal(byteContent);
return result;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/*
* @param content:
* @param password:
*/
private static byte[] decrypt(byte[] content, String password) {
try {// Use static code blocks to generate KeyGenerator object
//KeyGenerator kgen = KeyGenerator.getInstance(AES);
// use 128 position
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] encodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(encodeFormat, AES);
// Cipher The object actually does the encryption
Cipher cipher = Cipher.getInstance(AES);
// Initialize with a key Cipher object
cipher.init(Cipher.DECRYPT_MODE, key);
// Officially execute the decryption operation
byte[] result = cipher.doFinal(content);
return result;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 2 Into the system -- " 106 Hexadecimal conversion
* @param buf
* @return
*/
private static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 106 Into the system -- " 2 Hexadecimal conversion
* @param hexStr
* @return
*/
private static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1) {
return null;
}
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
public static void main(String[] args) throws UnsupportedEncodingException {
long begin=new Date().getTime();
String content = "aaades Encryption test ";
String password = "12345678dd";
// encryption
System.out.println(" Encrypted before: " + content);
byte[] encryptResult = encrypt(content, password);
String encryptResultStr = parseByte2HexStr(encryptResult);
System.out.println(" After the encryption: " + encryptResultStr);
// decryption
byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);
byte[] decryptResult = decrypt(decryptFrom, password);
// Decrypted content is decoded
String result = new String(decryptResult, UTF8);
System.out.println(" After decryption: " + result);
long end= new Date().getTime();
System.out.println(end-begin);
}
}
Note: SecureRandom is the sequence of generating safe random Numbers, password.getBytes () is the seed, as long as the seed is the same, the sequence is 1, so as long as there is password for decryption, the sequence can be restored.
PS: about encryption and decryption interested friends can also refer to the website online tools:
Password security online detection:
http://tools.ofstack.com/password/my_password_safe
High strength password generator:
http://tools.ofstack.com/password/CreateStrongPassword
Thunderbolt, express, whirlwind URL encryption/decryption tools:
http://tools.ofstack.com/password/urlrethunder
Online hash/hash algorithm encryption tool:
http://tools.ofstack.com/password/hash_encrypt
MD5/hash/ SHA-1 / SHA-2 / SHA-256 / SHA-512 / SHA-3 / RIPEMD-160 encryption tools:
http://tools.ofstack.com/password/hash_md5_sha
Online sha1 sha224 / sha256 sha384 / sha512 encryption tools:
http://tools.ofstack.com/password/sha_encode
I hope this article is helpful to you java programming.