JCE暗号化-データ暗号化標準(DES)チュートリアル
この記事では、Java Cryptography Extension (JCE)
を使用して、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");
Note
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を復号化モードにし、Cipher.doFinal()
メソッドでも復号化します。
desCipher.init(Cipher.DECRYPT_MODE, myDesKey); byte[] textDecrypted = desCipher.doFinal(textEncrypted);
6. 完全な例
JavaのJCEを使用して、DESメカニズムでテキストを暗号化および復号化する方法を示す完全な例。
package com.example.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暗号化アーキテクチャ–http://java.sun.com/j2se/1.5.0/docs/guide/security/CryptoSpec.html