Java(二)-非对称加密

rsa

公钥说明书X509EncodedKeySpec
私钥说明书PKCS8EncodedKeySpec
1.rsa util

package encrypt;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;

public class RSAUtil {
    public static String pubKeyEncryptData(String data, PublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String priDecryptData(String data, PrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decData = cipher.doFinal(Base64.getDecoder().decode(data));
            return new String(decData, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void createKeyRSA() {
        Security.addProvider(new BouncyCastleProvider());
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(512, new SecureRandom());
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            PrivateKey privateKey = keyPair.getPrivate();
            PublicKey publicKey = keyPair.getPublic();
            String strPublicKey = new String(Base64.getEncoder().encode(publicKey.getEncoded()));
            String strPrivateKey = new String(Base64.getEncoder().encode(privateKey.getEncoded()));
            System.out.println("pub:" + strPublicKey);
            System.out.println("pri:" + strPrivateKey);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

}

2.主函数调用

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class Main {
    public static void main(String[] args) {
        String src = "123456";
        RSAUtil.createKeyRSA();
        String strPriKey = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAyeVsQuvWAcrwCPUOmjxx0zLDTAexmEoFKPGFcMFf5Q1iVTdrlxSYM99sMJQoIQJ/dk+L7//b1XUqVO6A/nDhQQIDAQABAkEAhZB9Wphib7Utrv9PtcGfG7VNdhLw7mqplziQqtOC+SgAsT9QgFZZR/jtLUBacPPr356xEH2XqPMXp1aD4BtUAQIhAOhkhJ+QsoJzP0BAIpqabkwyJI67736xYNvSOBaM2raRAiEA3mfUZUlxTy3A2k0W7khaoyZAelCgY1Zq42MA+9jHt7ECIEstoV3BQI5E3BRb6xXamY3atsrZ70sr9KqIIg7heCuRAiAf97SjymarBtyNhD8jiOreQIVMD4K+RJGglX5ytLogQQIhALbUb2NRPBAgg9dCl2LARcF4OY9DNUBDpvCgeDRoXu9H";
        String strPubKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMnlbELr1gHK8Aj1Dpo8cdMyw0wHsZhKBSjxhXDBX+UNYlU3a5cUmDPfbDCUKCECf3ZPi+//29V1KlTugP5w4UECAwEAAQ==";
        try {
            //公钥规则对象
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(strPubKey.getBytes()));
           //私钥规则对象
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec=new PKCS8EncodedKeySpec(Base64.getDecoder().decode(strPriKey.getBytes()));
            KeyFactory keyFactory=KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

            //1.公钥加密
            String encryptData = RSAUtil.pubKeyEncryptData(src, publicKey);
            System.out.println(encryptData);
            String decryptData = RSAUtil.priDecryptData(encryptData, privateKey);
            System.out.println(decryptData);


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

你可能感兴趣的:(Java(二)-非对称加密)