中指定三个参数.密钥文件,更新验证的字符串和签名文件.
import java.security.*;
import java.io.*;
public class SignVerify
{
public static void main(String[] args)
{
if(args.length!=3)
{
System.out.println("Usage: java SignVerify KeyFile String SigFile");
System.exit(1);
}
SignVerify obj=new SignVerify();
try{
obj.verify(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 verify(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();
FileInputStream fis1=new FileInputStream(sigFile);
ObjectInputStream ois1=new ObjectInputStream(fis1);
byte[] b=(byte[])ois1.readObject();
fis1.close();
ois1.close();
Signature sig=Signature.getInstance("SHA1WithDSA");
sig.initVerify(pubKey);
sig.update(str.getBytes());
if(sig.verify(b))
{
System.out.println("Verify OK!");
}
else
{
System.out.println("Verify Error!");
}
}
}
在验证过程中,密钥对,字符串和签名一个都不能错,否则无法通过验证. |