MD5WithRSA

package com.fintech.common;

import com.qq.connect.utils.http.BASE64Encoder;
import org.apache.commons.codec.binary.Hex;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;

public class MD5WithRSA {

    private static final String publicKeyFileName = System.getProperty("user.dir") + File.separator + "pubkey.cer";
    private static final String privateKeyFileName = System.getProperty("user.dir") + File.separator + "private.pfx";
    private static final String pfxPassword = "123";//私钥文件获取时设置的密钥
    private static String aliasName = "003";//alias名称

    /**
     * 签名
     *
     * @return 签名后经过base64处理的字符串
     * @throws Exception
     */
    public static String Sign(String str) {
        String base64Sign = "";
        InputStream fis = null;
        try {
            fis = new FileInputStream(privateKeyFileName);//获取公钥文件流
            KeyStore keyStore = KeyStore.getInstance("RSA");//RSA
            char[] pscs = pfxPassword.toCharArray();
            keyStore.load(fis, pscs);
            PrivateKey priKey = (PrivateKey) (keyStore.getKey(aliasName, pscs));
            // 签名
            Signature sign = Signature.getInstance("MD5withRSA");
            sign.initSign(priKey);
            byte[] bysData = str.getBytes("UTF-8");
            sign.update(bysData);
            byte[] signByte = sign.sign();
            BASE64Encoder encoder = new BASE64Encoder();
            base64Sign = encoder.encode(signByte);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64Sign;
    }


//    public byte[] Sign(String src) {
//        byte[] result = new byte[0];
//        try {
//            //1.初始化密钥
//            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
//            keyPairGenerator.initialize(512);
//            KeyPair keyPair = keyPairGenerator.generateKeyPair();
//            RSAPublicKey rsaPublicKey = (RSAPublicKey)keyPair.getPublic();
//            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)keyPair.getPrivate();
//
//            //2.执行签名
//            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
//            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
//            Signature signature = Signature.getInstance("MD5withRSA");
//            signature.initSign(privateKey);
//            signature.update(src.getBytes());
//            result = signature.sign();
//            return result;
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return result;
//    }

//    public boolean VerifySign(byte[] result, String src) {
//        boolean bool = false;
//        try {
//            //1.初始化密钥
//            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
//            keyPairGenerator.initialize(512);
//            KeyPair keyPair = keyPairGenerator.generateKeyPair();
//            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
//            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
//
//            //2.验证签名
//            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
//            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
//            Signature signature = Signature.getInstance("MD5withRSA");
//            signature.initVerify(publicKey);
//            signature.update(src.getBytes());
//            bool = signature.verify(result);
//            return bool;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return bool;
//    }

    /**
     * 数据验证
     *
     * @param signStr 加密后的数据
     * @param verStr  原始字符
     * @return
     */
    public static boolean verify(String signStr, String verStr)throws Exception {
        boolean verfy = false;
        InputStream fis = null;
        try {
            fis = new FileInputStream(publicKeyFileName);
            CertificateFactory cf = CertificateFactory.getInstance("RSA");
            Certificate cerCert = (Certificate) cf.generateCertificate(fis);
            PublicKey pubKey = cerCert.getPublicKey();
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] signed = decoder.decodeBuffer(signStr);
            Signature sign = Signature.getInstance("MD5withRSA");
            sign.initVerify(pubKey);
            sign.update(verStr.getBytes("UTF-8"));
            verfy = sign.verify(signed);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return verfy;
    }

    /**
     * 通过私钥文件进行解密数据
     *
     * @return 解密后的明文字符串
     */
    public static String decode(String source) throws Exception {
        BASE64Decoder b64d = new BASE64Decoder();
        byte[] keyByte = b64d.decodeBuffer(source);
        InputStream fis = null;
        try {
            fis = new FileInputStream(privateKeyFileName);
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            char[] pscs = pfxPassword.toCharArray();
            keyStore.load(fis, pscs);
            PrivateKey priKey = (PrivateKey) (keyStore.getKey(aliasName, pscs));
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            byte[] epByte = cipher.doFinal(keyByte);
            return new String(epByte, "UTF-8");
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

posted @ 2018-12-28 10:42  爱吃醋的工程师  阅读(1764)  评论(0编辑  收藏  举报