Java AES Crypto Example

Advanced Encryption Standard (AES)

對稱式(symmetric)加密演算法, 詳細說明請參考Reference.

想得出這些演算法的人都是天才呀…

我試著理解定義並想著如果要實作出這個演算法該怎麼Coding…

最後決定只要會使用就好了…

Environment

JDK 1.6

Apache commons-codec 1.9

CIPHER_TRANSFORMATION: AES/CBC/NoPadding (128bit)

ENCRYPT: AES

KEY: 16 byte long, 128 bit = 16 * 8bit, same as key size

IV_KEY: 16 byte long, same as block size 128 bit

CHAR_ENCODING: UTF-8

BLOCK_SIZE: 16

Encrypt

Step 1. Append input text length to an exact multiple of 16. 加密的字串長度必需是16的倍數,不足者要補足。

byte[] data = plainText.getBytes(CHAR_ENCODING)
int dataByteLen = data.length;
int quotient = (int) Math.ceil(dataByteLen / (double) BLOCK_SIZE);
data = Arrays.copyOfRange(data, 0, BLOCK_SIZE * quotient);

Step 2. Generate Cipher and encrypt

Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
SecretKeySpec secretKeySpecy = new SecretKeySpec(KEY.getBytes(CHAR_ENCODING), ENCRYPT);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpecy, new IvParameterSpec(IV_KEY.getBytes(CHAR_ENCODING)));
byte[] cipherConvertText = cipher.doFinal(data);

Step 3. Use Base64 to encode binary data

Base64.encodeBase64String(cipherConvertText);

Decrypt

Step 1. Use Base64 to decode data

byte[] data = Base64.decodeBase64(encryptedText);

Step 2. Generate Cipher and decrypt

Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
SecretKeySpec secretKeySpecy = new SecretKeySpec(KEY.getBytes(CHAR_ENCODING), ENCRYPT);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpecy, new IvParameterSpec(IV_KEY.getBytes(CHAR_ENCODING)));
byte[] cipherConvertText = cipher.doFinal(data);

Step 3. Convert back to String

new String(cipherConvertText, CHAR_ENCODING);

Note: Cipher.getInstance(“AES”) means SunJCE default AES mode: AES/ECB/PKCS5Padding. ECB mode cannot use IV.

Reference

https://en.wikipedia.org/wiki/Advanced_Encryption_Standard

http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html

http://www.codedata.com.tw/social-coding/aes/

http://ijecorp.blogspot.tw/2013/08/python-m2crypto-aes-encrypt-decrypt.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s