如何在Jini,RMI和Applet中实现代码签名
时间:2011-07-06 it168
第一段代码:生成公开/私有密钥对并在命令行中指定文件,把密钥对写入该文件.
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();
}
}
如何在Jini,RMI和Applet中实现代码签名(2)
时间:2011-07-06 it168
第二段代码,命令行中指定存放密钥的文件,用于签名的字符串(这里使用字符串只是为了简单,其实在真正实际使用中应该换成用MD5或SHA1算法计算某一文件流的消息摘要值)和签名所存放的文件.功能是计算出签名并把该签名存放在文件中.
import java.security.*;
import java.io.*;
public class SignGen
{
public static void main(String[] args)
{
if(args.length!=3)
{
System.out.println("Usage: java SignGen KeyFile String SigFile");
System.exit(1);
}
SignGen obj=new SignGen();
try{
obj.genSignature(args[0],args[1],args[2]);
}catch(NoSuchAlgorithmException ex)
{
System.out.println("NoSuchAlgorithmException");
}
catch(InvalidKeyException ex)
{
System.out.println("InvalidKeyException");
}
catch(SignatureException ex)
{
System.out.println("SignatureException");
}
catch(ClassNotFoundException ex)
{
System.out.println("ClassNotFoundException");
}
catch(FileNotFoundException ex)
{
System.out.println("FileNotFoundException");
}
catch(IOException ex)
{
System.out.println("IOException");
}
}
public void genSignature(String keyFile,String str,String sigFile)
throws NoSuchAlgorithmException,InvalidKeyException,SignatureException,
ClassNotFoundException,FileNotFoundException,IOException
{
FileInputStream fis=new FileInputStream(keyFile);
ObjectInputStream ois=new ObjectInputStream(fis);
KeyPair kp=(KeyPair)ois.readObject();
PublicKey pubKey=kp.getPublic();
PrivateKey priKey=kp.getPrivate();
fis.close();
ois.close();
Signature sig=Signature.getInstance("SHA1WithDSA");
sig.initSign(priKey);
sig.update(str.getBytes());
byte[] b=sig.sign();
FileOutputStream fos=new FileOutputStream(sigFile);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(b);
fos.close();
oos.close();
}
}
如何在Jini,RMI和Applet中实现代码签名(3)
时间:2011-07-06 it168
第三段代码当然是用于验证签名了.命令行 |