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;
}
}