AES Encryption / Decryption for Java and C#


Java class for AES encryption and decryption that can share result with C#.

Code:
package text.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
* <p>Title: CipherUtil</p>
* <p>Description: Utility class for encrypt and decrypt string with AES algorithm, CBC mode, 128 bits</p>
* <p>Copyright: Copyright (c) 2014</p>
*
* @author [email protected]
* @version 1.0.0
*/
public class CipherUtil {

  /**
  * For testing
  * @param args
  * @throws Exception
  */
  public static void main(String[] args) throws Exception {
  CipherUtil cu = new CipherUtil();
  String strToEncrypt = "Hello Java";
  System.out.println("String to encrypt : "+new String(strToEncrypt));
  byte[] encryptedBytes = cu.getEncryptedData(strToEncrypt.getBytes());
  System.out.println("Encrypted message : "+new String(Base64Util.encode(encryptedBytes)));
  System.out.println("Decrypted message : "+new String(cu.getDecryptedData(encryptedBytes)));
 
  // Decrypt from external encryption
  String encodedStrToDecrypt = "zpRWg0Y/S6ddBlUL4VuhuA==";
  System.out.println("String to decrypt : "+encodedStrToDecrypt);
  String input = Base64Util.decodeString(encodedStrToDecrypt);
  byte[] decryptedBytes = cu.getDecryptedData(input.getBytes());
  System.out.println("Decrypted message2 : "+new String(decryptedBytes));
  }

  // Declare variables
  private String padding = "ISO10126Padding"; 
  private String keySpec = "thisIsAKey16bits";
  private String ivSpec = "hereA16bitIVspec";
  private byte[] keyBytes;
  private byte[] ivBytes;

  /**
  * Constructor
  */
  public CipherUtil() {
  this.keyBytes = keySpec.getBytes();
  this.ivBytes = ivSpec.getBytes();
  }

  /**
  * Constructor
  * @param keySpec
  * @param ivSpec
  * @throws Exception
  */
  public CipherUtil(String keySpec, String ivSpec) throws Exception {
  if (keySpec.length() == 16) {
  this.keySpec = keySpec;
  this.keyBytes = keySpec.getBytes();
  }
  else
  throw new Exception("Key spec length must be 16 bytes");
  if (ivSpec.length() == 16) {
  this.ivSpec = ivSpec;
  this.ivBytes = ivSpec.getBytes();
  }
  else
  throw new Exception("IV spec length must be 16 bytes");
  }

  /**
  * Encryption base
  * @param cipher
  * @param dataBytes
  * @return
  * @throws Exception
  */
  private byte[] encrypt(Cipher cipher, byte[] dataBytes) throws Exception{
  ByteArrayInputStream bIn = new ByteArrayInputStream(dataBytes);
  CipherInputStream cIn = new CipherInputStream(bIn, cipher);
  ByteArrayOutputStream bOut = new ByteArrayOutputStream();
  int ch;
  while ((ch = cIn.read()) >= 0) {
  bOut.write(ch);
  }
  return bOut.toByteArray();
  }

  /**
  * Decryption base
  * @param cipher
  * @param dataBytes
  * @return
  * @throws Exception
  */
  private byte[] decrypt(Cipher cipher, byte[] dataBytes) throws Exception{
  ByteArrayOutputStream bOut = new ByteArrayOutputStream();
  CipherOutputStream cOut = new CipherOutputStream(bOut, cipher);
  cOut.write(dataBytes);
  cOut.close();
  return bOut.toByteArray(); 
  }
 
  /**
  * Get encryption mode
  * @return cipher encryption
  * @throws Exception
  */
  private Cipher getAESCBCEncryptor() throws Exception{
  SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
  IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
  Cipher cipher = Cipher.getInstance("AES/CBC/"+padding);
  cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
  return cipher;
  }
 
  /**
  * Get decryption mode
  * @return cipher decryption
  * @throws Exception
  */
  private Cipher getAESCBCDecryptor() throws Exception{
  SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
  IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
  Cipher cipher = Cipher.getInstance("AES/CBC/"+padding);
  cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
  return cipher;
  }

  /**
  * Get encryption data
  * @param messageBytes
  * @return byte array
  * @throws Exception
  */
  public byte[] getEncryptedData(byte[] messageBytes) throws Exception {
  Cipher cipher = getAESCBCEncryptor();
  return encrypt(cipher, messageBytes);
  }

  /**
  * Get encryption string
  * @param messageBytes
  * @return string
  * @throws Exception
  */
  public String getEncryptedString(byte[] messageBytes) throws Exception {
  return new String(Base64Util.encode(getEncryptedData(messageBytes)));
  }

  /**
  * Get decryption data
  * @param encryptedMessageBytes
  * @return byte array
  * @throws Exception
  */
  public byte[] getDecryptedData(byte[] encryptedMessageBytes) throws Exception {
  Cipher decipher = getAESCBCDecryptor();
  return decrypt(decipher, encryptedMessageBytes);
  }
 
  /**
  * Get decryption string
  * @param encryptedMessageBytes
  * @return string
  * @throws Exception
  */
  public String getDecryptedString(byte[] encryptedMessageBytes) throws Exception {
  return new String(getDecryptedData(encryptedMessageBytes));
  }
 
}

Example result from Java.

Code:
String to encrypt : Hello Java
Encrypted message : F6b73SkEneMlRQNSmtF4sA==
Decrypted message : Hello Java
String to decrypt : xmFcq22TBiFMWR+XuGZ2HQ==
Decrypted message2 : Hello C#

Example code for C# http://www.gotoknow.org/dashboard/home#/posts/567073

คำสำคัญ (Tags): #AES Encryption
หมายเลขบันทึก: 567070เขียนเมื่อ 30 เมษายน 2014 15:25 น. ()แก้ไขเมื่อ 4 มิถุนายน 2014 22:25 น. ()สัญญาอนุญาต: ครีเอทีฟคอมมอนส์แบบ แสดงที่มา-ไม่ใช้เพื่อการค้า-ไม่ดัดแปลงจำนวนที่อ่านจำนวนที่อ่าน:


ความเห็น (0)

ไม่มีความเห็น

อนุญาตให้แสดงความเห็นได้เฉพาะสมาชิก
พบปัญหาการใช้งานกรุณาแจ้ง LINE ID @gotoknow
ClassStart
ระบบจัดการการเรียนการสอนผ่านอินเทอร์เน็ต
ทั้งเว็บทั้งแอปใช้งานฟรี
ClassStart Books
โครงการหนังสือจากคลาสสตาร์ท