2011-08-24

玩了一下AES加密解密

我將自己寫的程式碼貼上來,這是很簡短的程式,希望高手能稍加提點我自己不足之處。
import javax.crypto.Cipher;

import javax.crypto.spec.SecretKeySpec;

public class TestAES {

public static byte[] encrypt( byte[] msg ) throws Exception {
byte[] key = "vegafish12345678".getBytes(); // key 長度 = 16
return encrypt( key, msg );
}

public static byte[] encrypt( byte[] key, byte[] msg ) throws Exception {
if ( key.length != 16 ) {
throw new IllegalArgumentException( "Key length should be 16." );
}
SecretKeySpec spec = new SecretKeySpec( key, "AES" );
Cipher cipher = Cipher.getInstance( "AES" );
cipher.init( Cipher.ENCRYPT_MODE, spec );
return cipher.doFinal( msg );
}

public static byte[] decrypt( byte[] msg ) throws Exception {
byte[] key = "vegafish12345678".getBytes(); // key 長度 = 16
return decrypt( key, msg );
}

public static byte[] decrypt( byte[] key, byte[] msg ) throws Exception {
if ( key.length != 16 ) {
throw new IllegalArgumentException( "Key length should be 16." );
}
SecretKeySpec spec = new SecretKeySpec( key, "AES" );
Cipher cipher = Cipher.getInstance( "AES" );
cipher.init( Cipher.DECRYPT_MODE, spec );
return cipher.doFinal( msg );
}

public static void main( String[] args ) throws Exception {
String msg = "要被加密的訊息, the text would be encrypted.";

System.out.println( "原始String : " + msg );
System.out.println( "byte[]加密後: " + new String( encrypt( msg.getBytes() ) ) );
System.out.println( "byte[]解密後: " + new String( decrypt( encrypt( msg.getBytes() ) ) ) );
}

}

沒有留言: