Signature类用于提供数字签名,用于保证数据的完整性,用非对称密钥中的私钥签名,公钥验签。
Java的实现
签名
/**
* 签名算法
*/
public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
/**
* RSA签名
*
* @param content 待签名数据
* @param privateKey 私钥
* @param encode 字符集编码
* @return 签名值
*/
public static String sign(String content, PrivateKey privateKey, String encode) {
try {
Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
signature.initSign(privateKey);
signature.update(content.getBytes(encode));
byte[] signed = signature.sign();
return byte2Base64(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
检签
/**
* 验签
*
* @param content 待签名数据
* @param sign 签名值
* @param pubKey 公钥
* @return 失败时,返回false。
*/
public static boolean verifySignature(String content, String sign, PublicKey pubKey) {
if (null == content || null == sign || "".equals(content) || "".equals(sign)) {
return false;
}
try {
byte[] signed = base642Byte(sign);
Signature signatureChecker = Signature.getInstance(SIGN_ALGORITHMS);
signatureChecker.initVerify(pubKey);
signatureChecker.update(content.getBytes());
// 验证签名是否正常
return signatureChecker.verify(signed);
} catch (Exception e) {
return false;
}
}
public static String byte2Base64(byte[] bytes) {
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(bytes);
}
public static byte[] base642Byte(String base64Key) throws IOException {
BASE64Decoder decoder = new BASE64Decoder();
return decoder.decodeBuffer(base64Key);
}
测试
@Test
public void testSignature() throws Exception {
// 随机生成一对非对称加密的秘钥对
KeyPair keyPair = RSAUtil.getKeyPair();
String content = "helloWord123" + (new SecureRandom().nextLong() + "_测试内容");
System.out.println("验签内容:" + content);
String sign = SignatureUtil.sign(content, keyPair.getPrivate(), "utf-8");
System.out.println("签名结果=" + sign);
boolean verify = SignatureUtil.verifySignature(content, sign, keyPair.getPublic());
System.out.println("验签结果="+verify);
}
验签内容:helloWord123-1206901626301061997_测试内容
签名结果=HKY4rVCJ2tC0WJKe+J9siB0PWOz3uqzwg60gyfwT1tbmd9S00mOXeaIg/V6D/uLEkfC20d0fs9Sf
tP/zWNNklnVJLWfbGkLs8MlU0Mi1GGV6A8HozfWEnukzidTf4kx2iEU9LzETbcqbWflxlKKqShi6
lgdqKPC5wtC2byZjCIpAkutVE0u/GbtZQixyYJQbo/MODr8AC710gWJ8YS9WxIPntoeqoqkKC7Eg
47nAZsBgMAbtPZTFLhOJy1skTDhFwMx8cWKr6jrOBRZSfWNCmERU7Le3fkVjeg1UCKTDAQ3EMb0F
WeLWKvGnoUBi/iXABgR/PC8PM3m8ZPV/HmYH8A==
验签结果=true
Java-加密篇
Java加解-RSA加解密
Java加密-Signature数据签名
Java加密-AES加解密
Java加密-密钥的保存与获取