Keytool, Encryption, and Decryption

因為需要寫一個簡單的加解密程式,

所以稍微研究了一下 JAVA 所提供的 Keytool utility.

產生對稱 Secret Key 命令如下:

keytool -genseckey -keyalg “DESede” -alias “pwdkey” -keystore “pwdkey.jks” -storepass “***” -storetype“JCEKS”

-genseckey : 產生 Symmetric Key (DES)

-keyalg : 金鑰演算法

-alias : 別名 (whatever you like)

-keystore : 金鑰儲存庫 (存放金鑰的地方)

-storepass : 儲存庫密碼 (使用金鑰時需輸入此密碼)

-storetype : 儲存庫類型

keytool -list -v -storetype “JCEKS” -keystore “pwdkey.jks”

可顯示所產生的 key Info

JAVA Code For 加/解密 (fragment)

=============================

// Type of KeyStore

KeyStore keystore = KeyStore.getInstance(“JCEKS“);

// The pwd for reading pwdkey.jks

String keyPass = “***“;

// Retrieve pwdkey.jks

keystore.load(new FileInputStream(“pwdkey.jks“), keyPass.toCharArray());

// Retrieve generated key for encryption/decryption

Key key = keystore.getKey(“pwdkey“, keyPass.toCharArray());

System.out.println(“Key.Algorithm=” + key.getAlgorithm());
System.out.println(“Key.Format=” + key.getFormat());
System.out.println(“Key=” + new String(Base64.encode(key.getEncoded())));

// String for encryption
String str = “This is a test”;

// 加密

Cipher ecipher = Cipher.getInstance(key.getAlgorithm());
ecipher.init(Cipher.ENCRYPT_MODE, key);

byte[] out =  ecipher.doFinal(str.getBytes(“UTF-8”));

System.out.println(“Encrypt string=” + new String(Base64.encode(out)));

// 解密

Cipher dcipher = Cipher.getInstance(key.getAlgorithm());

dcipher.init(Cipher.DECRYPT_MODE, key);

byte[] restore = dcipher.doFinal(out);

System.out.println(“Decript string=” + new String(restore));

Reference:

keytool – Key and Certificate Management Tool

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