JAVA实现MD5WithRSA和SHA1WithRSA工具类


/**
 * Rsa 工具类
 */
public class Rsa {

    static{
           Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 
     * 载入公钥
     * @param publicKeyCer
     * @return
     * @throws FileNotFoundException
     * @throws CertificateException
     */
    public static PublicKey loadPublicKey(String publicKeyCer) throws FileNotFoundException, CertificateException {
        InputStream inStream = new FileInputStream(publicKeyCer);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
        PublicKey publicKey = cert.getPublicKey();
        return publicKey;
    }

    /**
     *  载入私钥
     * @param privateKeyPfx
     * @param password
     * @return
     * @throws Exception
     */
    public static PrivateKey loadPrivateKey(String privateKeyPfx,String password) throws Exception{
        // Create a keystore object
        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        char[] nPassword = (char[]) null;
        if ((password == null) || (password.trim().equals("")))
            nPassword = (char[]) null;
        else {
            nPassword = password.toCharArray();
        }
        // Load the file into the keystore
        keyStore.load(new FileInputStream(privateKeyPfx), nPassword);
        String aliaesName = "";
        @SuppressWarnings("rawtypes")
        Enumeration enumer = keyStore.aliases();
        while (enumer.hasMoreElements()) {
            aliaesName = (String) enumer.nextElement();
            if (keyStore.isKeyEntry(aliaesName)){
                return (PrivateKey) (keyStore.getKey(aliaesName, nPassword));
            }
        }
        throw new Exception("没有找到匹配私钥:"+privateKeyPfx);

    }

    /**
     * RSA公钥加密
     * @param input
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static  byte[] encrypt(byte[] input,PublicKey publicKey) throws Exception{
        Cipher cipher = null;
        cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey); // 用公钥pubKey初始化此Cipher
        return cipher.doFinal(input);                 //加密
    }

    /**
     * RSA私钥解密
     * @param input
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static  byte[] decrypt(byte[] input, PrivateKey privateKey)  throws Exception{
        Cipher cipher = null;
        cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey); // 用私钥priKey初始化此cipher
        return cipher.doFinal(input); 
    }

    /**
     * 产生SHA1WithRSA 签名
     * @param plainText
     * @return
     * @throws Exception
     */
    public static  byte[] signSha1WithRsa(byte[] plainText,PrivateKey privateKey) throws Exception {
        return  sign(plainText, SignatureMethod.SHA1WithRSA,privateKey);
    }

    /**
     * 验证SHA1WithRSA 签名信息
     * @param signature
     * @param plainText
     * @return
     * @throws Exception
     */
    public static  boolean verfySha1WithRsa(byte[] signature,byte[] plainText,PublicKey publicKey) throws Exception {
        return verfy(signature, plainText, SignatureMethod.SHA1WithRSA,publicKey);
    }

    /**
     * 产生MD5WithRSA签名信息
     * @param plainText
     * @return
     * @throws Exception
     */
    public static  byte[] signMd5WithRsa(byte[] plainText,PrivateKey privateKey) throws Exception {
        return sign(plainText, SignatureMethod.MD5WithRSA,privateKey);
    }

    /**
     * 验证MD5WithRSA签名信息
     * @param signature
     * @param plainText
     * @return
     * @throws Exception
     */
    public static  boolean verfyMd5WithRsa(byte[] signature,byte[] plainText,PublicKey publicKey) throws Exception {
        return verfy(signature, plainText, SignatureMethod.MD5WithRSA,publicKey);
    }

    /**
     *  产生RSA签名信息(指定签名方法)
     * @param plainText
     * @param signatureMethod
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static  byte[] sign(byte[] plainText,String signatureMethod ,PrivateKey privateKey) throws Exception {
        Signature sig = Signature.getInstance(signatureMethod,new BouncyCastleProvider());
        sig.initSign(privateKey);  //用此私钥初始化此签名对象Signature
        sig.update(plainText);          
        return sig.sign();         //签名
    }

    /**
     * 验证RSA签名信息(指定签名方法)
     * @param signature
     * @param plainText
     * @param signatureMethod
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static  boolean verfy(byte[] signature,byte[] plainText,String signatureMethod,PublicKey publicKey) throws Exception{
        Signature sig = Signature.getInstance(signatureMethod);
        sig.initVerify(publicKey);  // 用公钥初始化此用于Signature对象。
        sig.update(plainText);           
        return sig.verify(signature);     //签名验证 
    }
}

class SignatureMethod {
     public static String MD5WithRSA = "MD5WithRSA";
    public static String SHA1WithRSA = "SHA1WithRSA";

}
以下是一个使用Java编写的SHA256withRSA工具类的示例: ```java import java.security.Key; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; public class SHA256withRSAUtil { /** * 用私钥对信息生成数字签名 * * @param data 已加密数据 * @param privateKey 私钥(BASE64编码) * * @return * @throws Exception */ public static String sign(byte[] data, String privateKey) throws Exception { byte[] keyBytes = Base64.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(priKey); signature.update(data); return Base64.encode(signature.sign()); } /** * 校验数字签名 * * @param data 已加密数据 * @param publicKey 公钥(BASE64编码) * @param sign 数字签名 * * @return * @throws Exception * */ public static boolean verify(byte[] data, String publicKey, String sign) throws Exception { byte[] keyBytes = Base64.decode(publicKey); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey pubKey = keyFactory.generatePublic(keySpec); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initVerify(pubKey); signature.update(data); return signature.verify(Base64.decode(sign)); } /** * 私钥解密 * * @param encryptedData 已加密数据 * @param privateKey 私钥(BASE64编码) * @return * @throws Exception */ public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception { byte[] keyBytes = Base64.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateK); return cipher.doFinal(encryptedData); } /** * 公钥加密 * * @param data 源数据 * @param publicKey 公钥(BASE64编码) * @return * @throws Exception */ public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception { byte[] keyBytes = Base64.decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); Key publicK = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicK); return cipher.doFinal(data); } } ``` 注意:此工具类需要依赖Base64编码工具类,可以使用Java 8自带的Base64类或其他第三方库来实现
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值