import java.security.*;
import javax.crypto.*;
public class CipherTest{
public static void main(String[] args){
try{
/* 暗号化の設定 */
// 暗号鍵
byte[] keydata = {
(byte)0x00, (byte)0x01, (byte)0x02, (byte)0x03,
(byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07,
(byte)0x08, (byte)0x09, (byte)0x0a, (byte)0x0b,
(byte)0x0c, (byte)0x0d, (byte)0x0e, (byte)0x0f,
(byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13,
(byte)0x14, (byte)0x15, (byte)0x16, (byte)0x17,
};
// 暗号化アルゴリズム(トリプルDES)
String algorithm = "DESede";
// 平文
String clearTextString = "I wanna be with you.";
// エンコーディング
String encoding = "US-ASCII";
/* 暗号化処理 */
// javax.crypto.spec.DESedeKeySpec ってのもあるよ (・∀・)
SecretKey key = new SecretKeySpec(keydata, algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
// 平文
byte[] clearText = clearTextString.getBytes(encoding);
// 暗号化
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedText = cipher.doFinal(clearText);
// 復号化
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedText = cipher.doFinal(encryptedText);
/* 表示 */
System.out.println("********************************************");
System.out.println("平文");
System.out.println("文字列=" + new String(clearText, encoding));
System.out.println("16進=" + bytesToString(clearText));
System.out.println("********************************************");
System.out.println("暗号化された文字列");
System.out.println("文字列=" + new String(encryptedText, encoding));
System.out.println("16進=" + bytesToString(encryptedText));
System.out.println("********************************************");
System.out.println("復号化された文字列");
System.out.println("文字列=" + new String(decryptedText, encoding));
System.out.println("16進=" + bytesToString(decryptedText));
System.out.println("********************************************");
}catch(Exception e){
e.printStackTrace();
}
}
// byteの配列を16進表記に変換する。
private static String bytesToString(byte[] b){
if(b == null) return null;
StringBuffer sb = null;
sb = new StringBuffer();
for(int i = 0; i < b.length; i++){
sb.append(Integer.toString((int)((b[i] >> 4) & 0x0F), 16));
sb.append(Integer.toString((int)(b[i] & 0x0F), 16));
}
return sb.toString().toUpperCase();
}
}
tags: zlashdot Java Java
Posted by NI-Lab. (@nilab)
コメント
3DES暗号化。
投稿者: NI-Lab. | 2006年11月04日 08:43