RSA加密

RSA算法是一种非对称密码算法,所谓非对称,就是指该算法需要一对密钥,使用其中一个加密,则需要用另一个才能解密。

  我们接下来看下Java中如何实现RSA加密解密与加签验签。我们先来看RSA加密解密。  

 

 private static Map<Integer, String> keyMap = new HashMap<Integer, String>();  //用于封装随机产生的公钥与私钥
    public static void main(String[] args) throws Exception {
        //生成公钥和私钥
        genKeyPair();
        //加密字符串
        String message = "abc123哈喽";
        System.out.println("随机生成的公钥为:" + keyMap.get(0));
        System.out.println("随机生成的私钥为:" + keyMap.get(1));
        String messageEn = encrypt(message,keyMap.get(0));
        System.out.println(message + "\t加密后的字符串为:" + messageEn);
        String messageDe = decrypt(messageEn,keyMap.get(1));
        System.out.println("还原后的字符串为:" + messageDe);
    }

    /**
     * 随机生成密钥对
     * @throws NoSuchAlgorithmException
     */
    public static void genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器,密钥大小为96-1024位
        keyPairGen.initialize(1024,new SecureRandom());
        // 生成一个密钥对,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
//        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        String publicKeyString = new String(publicKey.getEncoded());
        // 得到私钥字符串
//        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        String privateKeyString = new String(privateKey.getEncoded());
        // 将公钥和私钥保存到Map
        keyMap.put(0,publicKeyString);  //0表示公钥
        keyMap.put(1,privateKeyString);  //1表示私钥
    }
    /**
     * RSA公钥加密
     *
     * @param str
     *            加密字符串
     * @param publicKey
     *            公钥
     * @return 密文
     * @throws Exception
     *             加密过程中的异常信息
     */
    public static String encrypt( String str, String publicKey ) throws Exception{
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }

    /**
     * RSA私钥解密
     *
     * @param str
     *            加密字符串
     * @param privateKey
     *            私钥
     * @return 铭文
     * @throws Exception
     *             解密过程中的异常信息
     */
    public static String decrypt(String str, String privateKey) throws Exception{
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }

随机生成的公钥为:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCUksU/xiRFTHEFHlW05q/Gnbt1FBJI2Ts/JIoYW7i3nw/j/kvQIAVW4/qanmsvqUJmgjJ0CwDe4ZBuK63Vcfz35OMiPeYTpZKxuHPsbyhptZJI0gox3L5cn0SVR1Al+lumfYmnvY/ct1AL3GLuXiP6z8uyqWhH4Me9YKnRXQVT6QIDAQAB
随机生成的私钥为:MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJSSxT/GJEVMcQUeVbTmr8adu3UUEkjZOz8kihhbuLefD+P+S9AgBVbj+pqeay+pQmaCMnQLAN7hkG4rrdVx/Pfk4yI95hOlkrG4c+xvKGm1kkjSCjHcvlyfRJVHUCX6W6Z9iae9j9y3UAvcYu5eI/rPy7KpaEfgx71gqdFdBVPpAgMBAAECgYEAg1y1zCpLvX3V2/mzO8xPlCO4L888T27KZIzRELJgQvH/Yc1giLcXIXlXBUiWasCTtgDdzR5Bec8kHVS/UR6E0+VFE+CtRAOVAuY6C6FKd+BgfNyXx1ETL40XY7dI83uXJqr9F/+p2W6NE8IDI+T9SJEda6Q9NvwzDSgCllKLxuUCQQDvayednv22E/PTvb/VoLyDfA6EheH0ciVBnNFynS+RQNkfhAdSQuS69s0sIpe9EV56WWieG6FPXwgzcNSAmkZ7AkEAntzyagURswjuAjOvcPNMQKa8BxUhLLU837QNXp8B7iZBxGoIwDlKY1+r8v+ntjvqlnYm0Q/sq7RmQglvfmqT6wJBAJZy8KcVBPvJF/ykDYuSAURizcCrXS0+GXlcsSVj70NIy+gJEIy56oAunQmyB0ZRRtx9mMdaN4joAABLU84opEcCQFtB0uNCPDObapXLOPnqWSA+Z36uDZuQFQLwfEmhj8tNILSCsLozbt7841q4r4/IhW6fOpcXzb2o6KEAqJJ3CLcCQHBEP96Poe7sdpiUoNoQbpquVajWktBQW2NoISqgTFkPxs5O0b5W0/agjWbY4px8uywveBzZm+kTKBFCwiQtkZQ=
abc123哈喽    加密后的字符串为:DWVzM3iLeVQefwPIdV13ENZtSPo0u6t+zU435E3gtwmBugRzF+1gNIW2aDij1BZroGkFVtdW0GMs1KilZ53xTB+04uVHjbmfxa6WHwUfodlt+PFVhlPG/ugv1Uh2qOYYEvw8Opnqi4DzXPyp0G4+EauJcBuPasf96sGbGHZmwk8=
还原后的字符串为:abc123哈喽

 

 

https://blog.csdn.net/qy20115549/article/details/83105736

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值