数字签名
程序员文章站
2022-07-09 11:50:47
...
package com.test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
public class Sign {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
Sign sign = new Sign();
sign.sign();
sign.verify();
}
public void sign() throws Exception{
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = kpg.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
Signature sign = Signature.getInstance("SHA1withRSA");
sign.initSign(privateKey);
sign.update("测试数据".getBytes());
byte[] data = sign.sign();
saveKey(publicKey, "sign_publicKey");
saveData(data, "sign_data");
}
public void verify() throws Exception{
PublicKey publicKey = (PublicKey)readKey("sign_publicKey");
Signature sign = Signature.getInstance("SHA1withRSA");
sign.initVerify(publicKey);
sign.update("测试数据".getBytes());
byte[] data = readData("sign_data");
boolean rs = sign.verify(data);
System.out.println(rs);
}
public void saveData(byte[] data, String fileName) throws Exception{
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(data);
oos.close();
fos.close();
}
public void saveKey(Key key, String fileName) throws Exception{
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(key);
oos.close();
fos.close();
}
public Key readKey(String fileName) throws Exception{
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
Key privateKey = (Key)ois.readObject();
return privateKey;
}
public byte[] readData(String fileName) throws Exception{
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
byte[] data = (byte[])ois.readObject();
return data;
}
}
上一篇: hibernate的一对多关系
下一篇: 数字签名