RSA---应用最广泛的非对称加密算法

Posted i-hard-working

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RSA---应用最广泛的非对称加密算法相关的知识,希望对你有一定的参考价值。

package com.ant.jdk8.encrypt;

import org.apache.commons.io.FileUtils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.*;
import java.util.Base64;

public class RSADemo {
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException,
            InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException {
        String data = "城头变幻大王旗";
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        String publicKeyBase64String = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        FileUtils.writeStringToFile(new File("D:\\rsa_public_key.pem"),publicKeyBase64String, Charset.forName("UTF-8"));
        PrivateKey privateKey = keyPair.getPrivate();
        String privateKeyBase64String = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        FileUtils.writeStringToFile(new File("D:\\rsa_private_key.pem"),privateKeyBase64String, Charset.forName("UTF-8"));
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE,publicKey);
        byte[] bytesEncrypt = cipher.doFinal(data.getBytes());
        byte[] encodeBase64 = Base64.getEncoder().encode(bytesEncrypt);
        System.out.println("加密后的数据:"+new String(encodeBase64));
        byte[] bytesDecode = Base64.getDecoder().decode(encodeBase64);
        cipher.init(Cipher.DECRYPT_MODE,privateKey);
        byte[] bytesDecrypt = cipher.doFinal(bytesDecode);
        System.out.println("解密后的数据:"+new String(bytesDecrypt));
    }
}
加密后的数据:f1AwqGViD4QIWl6wT97ootrxh/Qh43CtdRJpHXSVIQVIQuHqoJBlmJjFlPSLuVnxEdpGozeBnQ+U5ogZyumZ809uv9pV2I5A0KWQEotWkiVIe+EJyJROwAKQ2gnarg5EmWo5eMYrLl1FYp6iLogmP1lMnP8IFeJ6P9K+qYwASJ7dFLa5dtt12AsLiL4buxslOnFdxrBvBEVyiKA4ZCyNXTIbL2JoxyM7zLO+SXLtomuOaa96qS6XmnVZLFEuk955OpDDPWWHHk9v4H8NWEoBnUr9cv0/P0fhibPKdO4ImDW31bLI949O3KksMPfMBQVld2wx+dsVeAX117UhmE/vYA==
解密后的数据:城头变幻大王旗

rsa_public_key.pem:

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyi2BVZCaRRR/lQPEhsaaFZhVO4qVcV8+P85kjTTJ1mDeGdPoeEOJrB9K4tehx+DsRJdYl/n6Mftd9A/PWbHK0pN82z78q+w9UfInRV5+Prx3K4gCmpe8PKKIiVz+WnsGEj82/zTMLBCn31ksWpoCoISPwnGzopPxaji0d30wfZVziHTVHUi5iJRjHY7jn8nW0+v3s/oRfvJNZGMMoVmWogmQkmAW6DEngmRswOYgBBjppKp6FjRx6oGw2MrvODy67zlOVQIuI4G12o/4ui6anX2XC6BB5ET1nmp4bLFYEEqryJ+lKi1reDB6zQ7N63bt2B4go+qp0O3uybZuwC7OkwIDAQAB

rsa_private_key.pem:

MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDKLYFVkJpFFH+VA8SGxpoVmFU7ipVxXz4/zmSNNMnWYN4Z0+h4Q4msH0ri16HH4OxEl1iX+fox+130D89ZscrSk3zbPvyr7D1R8idFXn4+vHcriAKal7w8ooiJXP5aewYSPzb/NMwsEKffWSxamgKghI/CcbOik/FqOLR3fTB9lXOIdNUdSLmIlGMdjuOfydbT6/ez+hF+8k1kYwyhWZaiCZCSYBboMSeCZGzA5iAEGOmkqnoWNHHqgbDYyu84PLrvOU5VAi4jgbXaj/i6LpqdfZcLoEHkRPWeanhssVgQSqvIn6UqLWt4MHrNDs3rdu3YHiCj6qnQ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MlvQh097xzGsvUsBHLxEwrRis4AChK19mTNKA/YjpHHCXL+Q+269cgqo/gifUCjTGljS6pvjG5dqD71sovooGZahtvvTJ4/5mr9BS8Qb28MNPTDN9vd4VfyhBKtVL+6hRX+sPjypAHazkquIDkLYI1lrFzniH5F+nkBQ==

package com.ant.jdk8.encrypt;

import org.apache.commons.io.FileUtils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.File;
import java.io.IOException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtil {
    public static void main(String[] args) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException,
            IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchPaddingException {
        PublicKey publicKey = getPublicKey("D:\\rsa_public_key.pem");
        PrivateKey privateKey = getPrivateKey("D:\\rsa_private_key.pem");
        String encryptData = encryptData(publicKey,"城头变幻大王旗");
        String decryptData = decryptData(privateKey,encryptData);
        System.out.println(decryptData);
    }

    /**
     * 从磁盘上的公钥文件生成PublicKey
     * @param publicKeyPath
     * @return
     */
    public static PublicKey getPublicKey(String publicKeyPath) throws IOException, NoSuchAlgorithmException,
            InvalidKeySpecException {
        byte[] bytesPublicKeyBase64 = FileUtils.readFileToByteArray(new File(publicKeyPath));
        byte[] bytesPublicKey = Base64.getDecoder().decode(bytesPublicKeyBase64);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytesPublicKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     * 从磁盘上的私钥文件生成PrivateKey
     * @param privateKeyPath
     * @return
     */
    public static PrivateKey getPrivateKey(String privateKeyPath) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] bytesPrivateKeyBase64 = FileUtils.readFileToByteArray(new File(privateKeyPath));
        byte[] bytesPrivateKey = Base64.getDecoder().decode(bytesPrivateKeyBase64);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytesPrivateKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    public static String encryptData(PublicKey publicKey,String originalData) throws NoSuchPaddingException, NoSuchAlgorithmException,
            InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE,publicKey);
        byte[] bytesEncrypt = cipher.doFinal(originalData.getBytes());
        byte[] bytesEncryptBase64 = Base64.getEncoder().encode(bytesEncrypt);
        return new String(bytesEncryptBase64);
    }

    public static String decryptData(PrivateKey privateKey,String encryptData) throws NoSuchPaddingException, NoSuchAlgorithmException,
            InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        byte[] bytesEncrypt = Base64.getDecoder().decode(encryptData);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE,privateKey);
        byte[] bytesDecrypt = cipher.doFinal(bytesEncrypt);
        return new String(bytesDecrypt);
    }
}

技术分享图片

以上是关于RSA---应用最广泛的非对称加密算法的主要内容,如果未能解决你的问题,请参考以下文章

非对称加密的工程实践

RSA/SHA1加密和数字签名算法在开放平台中的应用

RSA加密算法原理

RSA算法特点及应用简述

非对称加密算法的主要算法

非对称加密技术- RSA算法数学原理分析