SHA1WithRSA 验证数字签名

该博客详细介绍了如何使用SHA1WithRSA算法进行数字签名的验证,包括使用公钥解密签名密文,更新明文内容,并通过Signature类进行签名验证。博主分享了在处理公钥数据时可能遇到的补码问题及其解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class SignProvider {
    
private SignProvider() {

    }

    
/**
     * 
     * Description:校验数字签名,此方法不会抛出任务异常,成功返回true,失败返回false,要求全部参数不能为空
     * 
     * 
@param pubKeyText
     *            公钥,base64编码
     * 
@param plainText
     *            明文
     * 
@param signTest
     *            数字签名的密文,base64编码
     * 
@return 校验成功返回true 失败返回false
     * 
@author 孙钰佳
     * 
@since:2007-12-27 上午09:33:55
     
*/
    
public static boolean verify(byte[] pubKeyText, String plainText,
            
byte[] signText) {
        
try {
            
// 取公钥匙对象
            java.security.PublicKey pubKey = getPublicKey(Base64
                    .decode(pubKeyText));
            
// 解密由base64编码的数字签名
            byte[] signed = Base64.decode(signText);
            java.security.Signature signatureChecker 
= java.security.Signature
                    .getInstance(
"SHA1WithRSA");
            signatureChecker.initVerify(pubKey);
            signatureChecker.update(plainText.getBytes());
            
// 验证签名是否正常
            if (signatureChecker.verify(signed))
                
return true;
            
else
                
return false;
        } 
catch (Throwable e) {
            System.out.println(
"校验签名失败");
            e.printStackTrace();
            
return false;
        }
    }

    
/**
     * 从公钥数据取得公钥
     * 
     * 
@param bPubKeyInput
     * 
@return
     
*/
    
public static PublicKey getPublicKey(byte[] bPubKeyInput) {
        PublicKey rsaPubKey 
= null;
        
byte[] bX509PubKeyHeader = { 48-127-9748136942-12272,
                
-122-913111503-127-1150 };
        
try {
            
byte[] bPubKey = new byte[bPubKeyInput.length
                    
+ bX509PubKeyHeader.length];
            System.arraycopy(bX509PubKeyHeader, 
0, bPubKey, 0,
                    bX509PubKeyHeader.length);
            System.arraycopy(bPubKeyInput, 
0, bPubKey,
                    bX509PubKeyHeader.length, bPubKeyInput.length);

            X509EncodedKeySpec rsaKeySpec 
= new X509EncodedKeySpec(bPubKey);
            KeyFactory keyFactory 
= KeyFactory.getInstance("RSA");
            rsaPubKey 
= keyFactory.generatePublic(rsaKeySpec);
        } 
catch (Exception e) {
            e.printStackTrace();
        }
        
return rsaPubKey;
    }
}
 这里要注意一些情况下根据公钥串取公约对象时要进行补码,当初因为不知道这个地方,郁闷了好久.嗨.....
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值