1.创建一个新的伪随机生成器对象并生成100字节的伪随机数,此随机数将用于生成DSA密钥对的一个种子。
2.用java.security.KeyPairGenerator的一个工厂化方法获取一个KeyPairGenerator对象。
3.用512比特的一个密钥长度和一个种子随机数初始化KeyPairGenerator对象。
4.由KeyPairGenerator对象生成KeyPair对象。
5.从KeyPair对象获取私钥和公钥,并将它们分别保存在文件DSApublic.key和文件DSAprivate.key中。
6.输出用base64编码格式表示。
举例:
public class GenKeys {
public static void main(String [] args) throws Exception {
SecureRandom sr = new SecureRandom();
byte [] pseudoRandom = new byte[100];
sr.nextBytes(pseudoRandom);
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
System.out.println("Initializing the DSA key pair generator...");
kpg.initialize(512, sr);
System.out.println("Generating DSA key pair...");
System.out.println("This may take a while...");
KeyPair kp = kpg.generateKeyPair();
System.out.println("DSA Public Key:");
Key pubKey = kp.getPublic();
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("DSApublic.key"));
out.writeObject(pubKey);
out.close();
} catch (Exception e) {
System.out.println("Could not save public key...");
System.out.println(e);
}
byte [] pubkeyBytes = pubKey.getEncoded();
System.out.println("Public key format is: " + pubKey.getFormat());
BASE64Encoder encoder = new BASE64Encoder();
String base64 = encoder.encode(pubkeyBytes);
System.out.println(base64);
System.out.println("DSA Private Key:");
Key privKey = kp.getPublic();
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("DSAprivate.key"));
out.writeObject(privKey);
out.close();
} catch (Exception e) {
System.out.println("Could not save private key...");
System.out.println(e);
}
byte [] privkeyBytes = privKey.getEncoded();
System.out.println("Private key format is: " + privKey.getFormat());
BASE64Encoder encoder2 = new BASE64Encoder();
base64 = encoder.encode(privkeyBytes);
System.out.println(base64);
}
}