background image

Java 代码:在 JiniRMI 和 Applet 中实现代码签名

第一段代码:生成公开/私有密钥对并在命令行中指定文件,把密钥对写入该文件.
  import java.security.*;
  import java.io.*;
  public class KeyPairGen
  {
  public static void main(String[] args)
  {
  if(args.length!=1)
  {
  System.out.println("Usage: java KeyPairGen KeyFile");
  System.exit(1);
  }
  KeyPairGen obj=new KeyPairGen();
  try{
  obj.gen(args[0]);
  }catch(NoSuchAlgorithmException ex)
  {
  System.out.println("NoSuchAlgorithmException");
  }
  catch(FileNotFoundException ex)
  {
  System.out.println("FileNotFoundException");
  }
  catch(IOException ex)
  {
  System.out.println("IOException");
  }
  }
  public void gen(String source) throws NoSuchAlgorithmException,
  FileNotFoundException,IOException
  {
  KeyPairGenerator kpGen=KeyPairGenerator.getInstance("DSA");
  kpGen.initialize(512);
  KeyPair kPair=kpGen.genKeyPair();
  FileOutputStream fos=new FileOutputStream(source);
  ObjectOutputStream oos=new ObjectOutputStream(fos);
  oos.writeObject(kPair);
  fos.close();
  oos.close();