Java-cryptography-keygenerator
提供:Dev Guides
Java暗号化-KeyGenerator
Javaは KeyGenerator クラスを提供します。このクラスは秘密鍵の生成に使用され、このクラスのオブジェクトは再利用可能です。
KeyGeneratorクラスを使用してキーを生成するには、以下の手順に従います。
ステップ1:KeyGeneratorオブジェクトを作成する
*KeyGenerator* クラスは、必要なキー生成アルゴリズムを表すString変数を受け入れ、秘密キーを生成するKeyGeneratorオブジェクトを返す* getInstance()*メソッドを提供します。
以下に示すように、* getInstance()メソッドを使用して *KeyGenerator オブジェクトを作成します。
//Creating a KeyGenerator object
KeyGenerator keyGen = KeyGenerator.getInstance("DES");
ステップ2:SecureRandomオブジェクトを作成する
*java.Security* パッケージの *SecureRandom* クラスは、Javaで乱数を生成するために使用される強力な乱数ジェネレーターを提供します。 以下に示すように、このクラスをインスタンス化します。
//Creating a SecureRandom object
SecureRandom secRandom = new SecureRandom();
ステップ3:KeyGeneratorを初期化する
*KeyGenerator* クラスは、* init()*という名前のメソッドを提供します。このメソッドはSecureRandomオブジェクトを受け入れ、現在の *KeyGenerator* を初期化します。
- init()*メソッドを使用して、前の手順で作成したKeyGeneratorオブジェクトを初期化します。
//Initializing the KeyGenerator
keyGen.init(secRandom);
例
次の例は、 javax.crypto パッケージのKeyGeneratorクラスを使用した秘密鍵の鍵生成を示しています。
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;
public class KeyGeneratorExample {
public static void main(String args[]) throws Exception{
//Creating a KeyGenerator object
KeyGenerator keyGen = KeyGenerator.getInstance("DES");
//Creating a SecureRandom object
SecureRandom secRandom = new SecureRandom();
//Initializing the KeyGenerator
keyGen.init(secRandom);
//Creating/Generating a key
Key key = keyGen.generateKey();
System.out.println(key);
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(cipher.ENCRYPT_MODE, key);
String msg = new String("Hi how are you");
byte[] bytes = cipher.doFinal(msg.getBytes());
System.out.println(bytes);
}
}
出力
上記のプログラムは、次の出力を生成します-
com.sun.crypto.provider.DESKey@18629
[B@2ac1fdc4