JAVA生成RSA公私钥对代码记录

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;

public class RSAUtil {

    private static final String KEY_ALGORITHM_RSA = "RSA";

    public static void main(String[] args) {
        genKeyPair();
    }

    /**
     * 生成RSA密钥对
     * RSA(SHA1WithRSA):对RSA密钥的长度不限制,推荐使用2048位以上
     * RSA2(SHA256WithRSA):(强烈推荐使用),强制要求RSA密钥的长度至少为2048.
     */
    private static void genKeyPair(){
        KeyPairGenerator keyPairGen;
        try {
            // 目前看algorithm有三种,DiffieHellman、DSA、RSA
            // 可参考:https://m.runoob.com/manual/jdk1.6/java.base/java/security/KeyPairGenerator.html
            keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM_RSA);
        } catch (NoSuchAlgorithmException var5) {
            throw new RuntimeException("生成秘钥异常", var5);
        }

        keyPairGen.initialize(2048);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
        System.out.println("公钥:" + new String(Base64.getEncoder().encode(publicKey.getEncoded())));
        System.out.println("私钥:" + new String(Base64.getEncoder().encode(privateKey.getEncoded())));
    }

}

你可能感兴趣的:(java)