数字签名【你的数据的数字摘要,用私钥加密,我用公钥解密成功,那说明这个数据就是你的】
你的公钥必须到公安机关或者权威机构去备案。
package com.xiongshiyan.security;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
//私钥加密 公钥解密
publicclass DataSign {
/**
* @param args
* @throws Exception
*/
publicstaticvoid main(String[] args) throws Exception {
// TODO Auto-generatedmethod stub
DataSign.sign();
DataSign.verify();
}
privatestaticvoid sign() throws Exception{
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");//非对称加密方式
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
Signature signature = Signature.getInstance("MD5WithRSA");
signature.initSign(privateKey);//私钥加密md5
signature.update("给你一百万,绝不反悔".getBytes());
byte[] signed=signature.sign();
//把加密后的数据和key一起给别人 别人拿到了之后进行恢复
ObjectOutputStream oosKey=new ObjectOutputStream(new FileOutputStream("key3.key"));
oosKey.writeObject(publicKey);//写入加密key
oosKey.close();
FileOutputStream oosDat=new FileOutputStream("dat3.dat");
oosDat.write(signed);//写入加密dat
oosDat.close();
}
privatestaticvoid verify() throws Exception{
Signature signature = Signature.getInstance("MD5WithRSA");
ObjectInputStream oisKey=new ObjectInputStream(new FileInputStream("key3.key"));
PublicKey publicKey=(PublicKey)oisKey.readObject();
oisKey.close();
signature.initVerify(publicKey);
signature.update("给你一百万,绝不反悔".getBytes());
FileInputStream fisDat=new FileInputStream("dat3.dat");
ByteArrayOutputStream baos=new ByteArrayOutputStream();
DataSign.copyStream(fisDat, baos);
byte[] deSecResult=baos.toByteArray();
boolean isYours=signature.verify(deSecResult);
System.out.println(isYours);
}
privatestaticvoid copyStream(InputStream is,OutputStream os) throws Exception{
byte[] buff=newbyte[1024];
int total=0;
int len=is.read(buff);
while(len!=-1){
os.write(buff, 0, len);
len=is.read(buff);
}
}
}