JCE暗号化 – データ暗号化標準(DES)チュートリアル
この記事では、「暗号化拡張(JCE)」を使用してhttp://en.wikipedia.org/wiki/Data
Encryption
Standard[データ暗号化標準(DES)]メカニズムを介してテキストを暗号化または復号化する方法を説明します。
1. DESキー
DESキーを作成します。
KeyGenerator keygenerator = KeyGenerator.getInstance("DES"); SecretKey myDesKey = keygenerator.generateKey();
2.暗号情報
CipherクラスからCipherインスタンスを作成し、次の情報をスラッシュ(/)で区切って指定します。
Cipher desCipher; //Create the cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
-
注** + DES =データ暗号化標準。 + ECB =電子コードブックモード。 + PKCS5Padding = PKCS#5スタイルのパディング。
この場合、電子コードブックモードでPKCS#5スタイルのパディングを使用してDES(データ暗号化標準)暗号を作成しました。
3.それを変換する
文字列をByte[]配列形式に変換します。
byte[]text = "No body can see me".getBytes();
4.それを暗号化する
Cipherを暗号化モードで作成し、 `Cipher.doFinal()`メソッドで暗号化します。
desCipher.init(Cipher.ENCRYPT__MODE, myDesKey); byte[]textEncrypted = desCipher.doFinal(text);
5.それを解読する
暗号を解読モードで作成し、 `Cipher.doFinal()`メソッドで解読します。
desCipher.init(Cipher.DECRYPT__MODE, myDesKey); byte[]textDecrypted = desCipher.doFinal(textEncrypted);
6.完全な例
JavaのJCEを使用してDESメカニズムのテキストを暗号化および復号化する方法を示す完全な例。
package com.mkyong.util; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; public class JEncrytion { public static void main(String[]argv) { try{ KeyGenerator keygenerator = KeyGenerator.getInstance("DES"); SecretKey myDesKey = keygenerator.generateKey(); Cipher desCipher; //Create the cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); //Initialize the cipher for encryption desCipher.init(Cipher.ENCRYPT__MODE, myDesKey); //sensitive information byte[]text = "No body can see me".getBytes(); System.out.println("Text[Byte Format]: " + text); System.out.println("Text : " + new String(text)); //Encrypt the text byte[]textEncrypted = desCipher.doFinal(text); System.out.println("Text Encryted : " + textEncrypted); //Initialize the same cipher for decryption desCipher.init(Cipher.DECRYPT__MODE, myDesKey); //Decrypt the text byte[]textDecrypted = desCipher.doFinal(textEncrypted); System.out.println("Text Decryted : " + new String(textDecrypted)); }catch(NoSuchAlgorithmException e){ e.printStackTrace(); }catch(NoSuchPaddingException e){ e.printStackTrace(); }catch(InvalidKeyException e){ e.printStackTrace(); }catch(IllegalBlockSizeException e){ e.printStackTrace(); }catch(BadPaddingException e){ e.printStackTrace(); } } }
出力
Text[Byte Format]:[B@19b5393 Text : No body can see me Text Encryted :[B@4e79f1 Text Decryted : No body can see me
リファレンス
-
JavaTM暗号化アーキテクチャ –