2010年2月2日 星期二

JCA Cipher加解密


JCA加密/解密的介紹:
使用Cipher進行
1.加/解密資料
2.使用Blowfish與OFB mode
3.人工產生IV(Initialization Vector)





import java.security.SecureRandom;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.crypto.Cipher;

import java.security.NoSuchAlgorithmException;

import java.security.InvalidKeyException;

import java.security.InvalidAlgorithmParameterException;

import javax.crypto.NoSuchPaddingException;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.BadPaddingException;

import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.codec.binary.Base64;



/**

*

* @author Frank Kim

*/

public class CipherWithIvExample {



public static void main(String args[]) {

try {

KeyGenerator kg = KeyGenerator.getInstance("Blowfish");

SecretKey sk = kg.generateKey();



byte[] origData = "data".getBytes();



Cipher cipher = Cipher.getInstance("Blowfish/OFB/PKCS5Padding");



byte[] randomBytes = new byte[8];

SecureRandom random = SecureRandom.getInstance("SHA1PRNG");

random.nextBytes(randomBytes);

IvParameterSpec ivSp1 = new IvParameterSpec(randomBytes);



cipher.init(Cipher.ENCRYPT_MODE, sk, ivSp1);

byte[] encryText = cipher.doFinal(origData);



byte[] iv = cipher.getIV();

IvParameterSpec ivSp2 = new IvParameterSpec(iv);



cipher.init(Cipher.DECRYPT_MODE, sk, ivSp2);

byte[] decryText = cipher.doFinal(encryText);



String origString = new String(origData);

String decryString = new String(decryText);

System.out.println("Data matches? " + origString.equals(decryString));



} catch (NoSuchAlgorithmException e1) {

System.err.println(e1);

} catch (InvalidKeyException e2) {

System.err.println(e2);

} catch (NoSuchPaddingException e3) {

System.err.println(e3);

}catch (IllegalBlockSizeException e4) {

System.err.println(e4);

} catch (BadPaddingException e5) {

System.err.println(e5);

} catch (InvalidAlgorithmParameterException e6) {

System.err.println(e6);

}

}



}

沒有留言: