SHA512withRSA,加解密验证

import org.apache.commons.codec.binary.Base64;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;


/**
 *  * 数字签名
 *  * 1:SHA512withRSA,:将正文通过SHA512数字摘要后,将密文 再次通过生成的RSA密钥加密,生成数字签名,
 *  * 将明文与密文以及公钥发送给对方,对方拿到私钥/公钥对数字签名进行解密,然后解密后的,与明文经过MD5加密进行比较
 *  * 如果一致则通过
 *  * 2:使用Signature的API来实现SHA512withRSA
 *  *
 *  
 */
public class SHA512withRSA {


    /**
     * 使用RSA生成一对钥匙
     *
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static KeyPair getKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        //生成返回带有公钥和私钥的对象
        KeyPair generateKeyPair = keyPairGenerator.generateKeyPair();
        return generateKeyPair;
    }

    /**
     * 生成私钥
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @return 
     */
    public static PrivateKey getPrivateKey(KeyPair key) {
        PrivateKey generatePrivate = null;
        try {
            PrivateKey private1 = key.getPrivate();
            byte[] encoded = private1.getEncoded();
            byte[] bytes = Base64.encodeBase64(encoded);
            String string = new String(bytes, "UTF-8");
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
            KeyFactory factory = KeyFactory.getInstance("RSA");
            generatePrivate = factory.generatePrivate(keySpec);
        } catch (Exception e) {
// TODO: handle exception
        }
        return generatePrivate;
    }

    /**
     * 私钥加密
     *
     * @throws BadPaddingException 
     * @throws IllegalBlockSizeException 
     */
    public static byte[] encrtpyByPrivateKey(byte[] bb, PrivateKey key) throws IllegalBlockSizeException, BadPaddingException {
        byte[] doFinal = null;
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            doFinal = cipher.doFinal(bb);
        } catch (Exception e) {
// TODO: handle exception
        }
        return doFinal;
    }

    /**
     * 获取公钥
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @return 
     */
    public static PublicKey getPublicKey(KeyPair keyPair) {
        PublicKey publicKey = null;
        try {
            PublicKey public1 = keyPair.getPublic();
            byte[] encoded = public1.getEncoded();
            byte[] bytes = Base64.encodeBase64(encoded);
            String string = new String(bytes, "UTF-8");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
            KeyFactory factory = KeyFactory.getInstance("RSA");
            publicKey = factory.generatePublic(keySpec);
        } catch (Exception e) {
        // TODO: handle exception
        }
        return publicKey;
    }

    /**
     * 使用公钥解密
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @return 
     */
    public static byte[] decodePublicKey(byte[] b, PublicKey key) {
        byte[] doFinal = null;
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, key);
            doFinal = cipher.doFinal(b);
        } catch (Exception e) {
// TODO: handle exception
        }
        return doFinal;
    }

    //通过SHA1加密
    public static byte[] encryptMD5(String str) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA1");
        byte[] digest2 = digest.digest(str.getBytes());
        return digest2;
    }

    //sign签名
    public static byte[] sign(String str, PrivateKey key) throws NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException {
        byte[] encryptMD5 = encryptMD5(str);
        byte[] encrtpyByPrivateKey = encrtpyByPrivateKey(encryptMD5, key);
        return encrtpyByPrivateKey;
    }

    //校验
    public static boolean verify(String str, byte[] sign, PublicKey key) throws NoSuchAlgorithmException {
        byte[] encryptMD5 = encryptMD5(str);
        byte[] decodePublicKey = decodePublicKey(sign, key);
        String a = new String(encryptMD5);
        String b = new String(decodePublicKey);
        if (a.equals(b)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Signature的用法
     * 数字签名
     *
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException 
     * @throws SignatureException 
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public static byte[] signMethod(String str, PrivateKey key) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    //初始化 MD5withRSA
        Signature signature = Signature.getInstance("SHA512withRSA");
    //使用私钥
        signature.initSign(key);
    //需要签名或校验的数据
        signature.update(str.getBytes());
        return signature.sign();//进行数字签名
    }

    /**
     * 数字校验
     *
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException 
     * @throws SignatureException 
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public static boolean verifyMethod(String str, byte[] sign, PublicKey key) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        Signature signature = Signature.getInstance("SHA512withRSA");
        signature.initVerify(key);
        signature.update(str.getBytes());
        return signature.verify(sign);
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, SignatureException {
        //获取钥匙对
        KeyPair keyPair = getKeyPair();
        //获取公钥
        PublicKey publicKey = getPublicKey(keyPair);
        //获取私钥
        PrivateKey privateKey = getPrivateKey(keyPair);

        /********************基于SignatureAPI签名*************************************/
        String signStr = "的方法十分士大夫";
        byte[] signMethod = signMethod(signStr, privateKey);

        boolean verifyMethod = verifyMethod(signStr, signMethod, publicKey);
        System.out.println("使用SignatureAPI 数字签名是否一致:" + verifyMethod);
    }
}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值