1、首先创建一个接口类(ISignature)
public interface ISignature {
public byte[] sign(byte[] content,String algorithm,PrivateKey privatekey);
public boolean verify(byte[] content,byte[] signature,String algorithm,PublicKey publickey);
}
2、
实现类(Sign)
public class Sign implements ISignature {
private static final Logger log = LoggerFactory.getLogger(Sign.class);
/**
* RSA签名
*
* @param content 待签内容
* @param algorithm 签名算法,例如:MD5WithRSA、SHA1WithRSA
* @param privatekey 私钥
* @return 签名
*/
@Override
public byte[] sign(byte[] content, String algorithm, PrivateKey privatekey) {
try {
//用私钥对信息生成数字签名
Signature stool = Signature.getInstance(algorithm);
stool.initSign(privatekey);
stool.update(content);
return stool.sign();
} catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException ex) {
log.warn("sign failure.",ex);
return null;
}
}
/**
* 校验签名
*
* @param content 待验内容
* @param signature 签名
* @param algorithm 签名算法,例如:MD5WithRSA、SHA1WithRSA
* @param publickey 公钥
* @return 是否有效签名
*/
@Override
public boolean verify(byte[] content,byte[] signature, String algorithm, PublicKey publickey) {
try {
Signature stool = Signature.getInstance(algorithm);
stool.initVerify(publickey);
stool.update(content);
//验证签名是否正常
return stool.verify(signature);
} catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException ex) {
log.warn("verify failure.",ex);
return false;
}
}