第一段代碼:生成公開/私有密鑰對並在命令行中指定文件
import java
import java
public class KeyPairGen
{
public static void main(String[] args)
{
if(args
{
System
System
}
KeyPairGen obj=new KeyPairGen();
try{
obj
}catch(NoSuchAlgorithmException ex)
{
System
}
catch(FileNotFoundException ex)
{
System
}
catch(IOException ex)
{
System
}
}
public void gen(String source) throws NoSuchAlgorithmException
FileNotFoundException
{
KeyPairGenerator kpGen=KeyPairGenerator
kpGen
KeyPair kPair=kpGen
FileOutputStream fos=new FileOutputStream(source);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos
fos
oos
}
}
第二段代碼
import java
import java
public class SignGen
{
public static void main(String[] args)
{
if(args
{
System
System
}
SignGen obj=new SignGen();
try{
obj
}catch(NoSuchAlgorithmException ex)
{
System
}
catch(InvalidKeyException ex)
{
System
}
catch(SignatureException ex)
{
System
}
catch(ClassNotFoundException ex)
{
System
}
catch(FileNotFoundException ex)
{
System
}
catch(IOException ex)
{
System
}
}
public void genSignature(String keyFile
throws NoSuchAlgorithmException
ClassNotFoundException
{
FileInputStream fis=new FileInputStream(keyFile);
ObjectInputStream ois=new ObjectInputStream(fis);
KeyPair kp=(KeyPair)ois
PublicKey pubKey=kp
PrivateKey priKey=kp
fis
ois
Signature sig=Signature
sig
sig
byte[] b=sig
FileOutputStream fos=new FileOutputStream(sigFile);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos
fos
oos
}
}
第三段代碼當然是用於驗證簽名了
import java
import java
public class SignVerify
{
public static void main(String[] args)
{
if(args
{
System
System
}
SignVerify obj=new SignVerify();
try{
obj
}catch(NoSuchAlgorithmException ex)
{
System
}
catch(InvalidKeyException ex)
{
System
}
catch(SignatureException ex)
{
System
}
catch(ClassNotFoundException ex)
{
System
}
catch(FileNotFoundException ex)
{
System
}
catch(IOException ex)
{
System
}
}
public void verify(String keyFile
NoSuchAlgorithmException
ClassNotFoundException
{
FileInputStream fis=new FileInputStream(keyFile);
ObjectInputStream ois=new ObjectInputStream(fis);
KeyPair kp=(KeyPair)ois
PublicKey pubKey=kp
PrivateKey priKey=kp
fis
ois
FileInputStream fis
ObjectInputStream ois
byte[] b=(byte[])ois
fis
ois
Signature sig=Signature
sig
sig
if(sig
{
System
}
else
{
System
}
}
}
在驗證過程中
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26967.html