RSA签名与RSA加密异同

RSA签名体制。签名体制同样包含3个算法:KeyGen(密钥生成算法),Sign(签名算法),Verify(验证算法).
私钥用于对数据进行签名,公钥用于对签名进行验证。

import org.apache.commons.codec.binary.Base64;
import java.io.IOException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author yxz
 *         <p>
 *         利用rsa生成一对公私钥
 *         SHA1withRSA进行签名与验签
 */
public class RSATest {

    private static final String PUBLIC_KEY ="publicKey";
    private static final String PRIVATE_KEY ="privateKey";

    private static final String KEY_ALGORITHM = "RSA";

    public static void main(String[] args) throws IOException {
        try {
            String pre="http://www.baidu.com?";
            TreeMap<String,Object> map=new TreeMap<>();
            map.put("source",108);
            map.put("merchant","3234343");
            map.put("userid",123323);
            StringBuilder sb=new StringBuilder();
            sb.append(pre);
            for(String temp:map.keySet()){
                sb.append(temp);
                sb.append("=");
                sb.append(map.get(temp));
                if(!temp.equals(map.lastKey())){
                    sb.append("&");
                }
            }
            String content=sb.toString();
            System.out.println(content);

            Map<String,String> keyMap = genKey();
            RSAPublicKey publicKey = getPublicKey(keyMap.get(PUBLIC_KEY));
            RSAPrivateKey privateKey = getPrivateKey(keyMap.get(PRIVATE_KEY));

            //SHA1withRSA算法进行签名
            Signature sign = Signature.getInstance("SHA1withRSA");
            sign.initSign(privateKey);
            byte[] data = content.getBytes("utf-8");
            //更新用于签名的数据
            sign.update(data);
            String signature=Base64.encodeBase64String(sign.sign());
            System.out.println(signature);

            Signature verifySign = Signature.getInstance("SHA1withRSA");
            verifySign.initVerify(publicKey);
            //用于验签的数据
            verifySign.update(data);

            boolean flag = verifySign.verify(Base64.decodeBase64(signature));
            System.out.println(flag);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static Map<String,String> genKey() throws NoSuchAlgorithmException{
        Map<String,String> keyMap = new HashMap<String,String>();
        KeyPairGenerator keygen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        SecureRandom random = new SecureRandom();
        // 初始加密,512位已被破解,用1024位,最好用2048位
        keygen.initialize(2048, random);
        // 取得密钥对
        KeyPair kp = keygen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey)kp.getPrivate();
        String privateKeyString = Base64.encodeBase64String(privateKey.getEncoded());
        RSAPublicKey publicKey = (RSAPublicKey)kp.getPublic();
        String publicKeyString = Base64.encodeBase64String(publicKey.getEncoded());
        keyMap.put(PUBLIC_KEY, publicKeyString);
        keyMap.put(PRIVATE_KEY, privateKeyString);
        return keyMap;
    }
   
    /**获取公钥私钥**/
    public static RSAPublicKey getPublicKey(String publicKey) throws Exception{
        byte[] keyBytes = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return (RSAPublicKey) keyFactory.generatePublic(spec);
    }

    public static RSAPrivateKey getPrivateKey(String privateKey) throws Exception{
        byte[] keyBytes = Base64.decodeBase64(privateKey);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return (RSAPrivateKey) keyFactory.generatePrivate(spec);
    }

/**RSA公钥加密体制包含如下3个算法:KeyGen(密钥生成算法),Encrypt(加密算法)以及Decrypt(解密算法)
公钥用于对数据进行加密,私钥用于对数据进行解密
**/
public static String encryptByPublicKey(String publicKey, String plainText) {
    byte[] publicKeyBytes = Base64Utils.decode(publicKey);
    byte[] textBytes = EncodesUtil.encode(plainText);
    byte[] encryptedBytes = encryptByPublicKey(publicKeyBytes, textBytes);

    return Base64Utils.encode(encryptedBytes);
}

public static byte[] encryptByPublicKey(byte[] publicKeyBytes, byte[] plainText) {
    try {
        PublicKey publicKey = getPublicKey(publicKeyBytes);
        Cipher cipher = Cipher.getInstance(ALGORITHMS);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(plainText);

        return encryptedBytes;
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

public static String decryptByPrivateKey(String privatKey, String encryptedText) {
    byte[] privateKeyBytes = Base64Utils.decode(privatKey);
    byte[] encryptedBytes = Base64Utils.decode(encryptedText);
    byte[] decryptedBytes = decryptByPrivateKey(privateKeyBytes, encryptedBytes);

    return EncodesUtil.decode(decryptedBytes);
}

public static byte[] decryptByPrivateKey(byte[] privateKeyBytes, byte[] encryptedBytes) {
    try {
        PrivateKey privateKey = getPrivateKey(privateKeyBytes);
        Cipher cipher = Cipher.getInstance(ALGORITHMS);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        return decryptedBytes;
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大巨魔战将

如果对您有帮助,请打赏1分钱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值