java - 在 Java 中从私有(private)获取公钥

标签 java public-key private-key

我记得很久以前用 OpenSSL 做过这个,但我想知道这是否可能以及如何实现,我从未在 java 上使用过密码学。

最佳答案

假设我们正在谈论 RSA 私钥和公钥。然后,如果您使用的是 PEM 格式文件,那么首先您需要将文件中的私钥读入 PrivateKey 对象:

    public PrivateKey readPemRsaPrivateKey(String pemFilename) throws
            java.io.IOException,
            java.security.NoSuchAlgorithmException,
            java.security.spec.InvalidKeySpecException
    {
            String pemString = File2String(pemFilename);

            pemString = pemString.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
            pemString = pemString.replace("-----END RSA PRIVATE KEY-----", "");

            byte[] decoded = Base64.decodeBase64(pemString);

            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decoded);
            KeyFactory kf = KeyFactory.getInstance("RSA");

            return kf.generatePrivate(keySpec);
    }

其中 File2String 类似于:

    private static String File2String(String fileName) throws
            java.io.FileNotFoundException, java.io.IOException
    {
            File file = new File(fileName);

            char[] buffer = null;

            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

            buffer = new char[(int)file.length()];

            int i = 0;
            int c = bufferedReader.read();

            while (c != -1) {
                    buffer[i++] = (char)c;
                    c = bufferedReader.read();
            }
            return new String(buffer);
    }

现在您可以使用如下代码生成相应的PublicKey:

    import java.security.interfaces.RSAPrivateCrtKey;
    import java.security.spec.RSAPublicKeySpec;

...

    PrivateKey myPrivateKey = readPemRsaPrivateKey(myPrivateKeyPemFileName);
    RSAPrivateCrtKey privk = (RSAPrivateCrtKey)myPrivateKey;

    RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(privk.getModulus(), privk.getPublicExponent());

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey myPublicKey = keyFactory.generatePublic(publicKeySpec);

致谢:How to get a RSA PublicKey by giving a PrivateKey?

关于java - 在 Java 中从私有(private)获取公钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8434428/

相关文章:

java - 如何重构单例的类层次结构,其中每个类都有一个 getInstance() 方法?

go - 从 Golang 中的证书获取 RSA 公钥

recaptcha - reCAPTCHA 的公钥和私钥有什么用?

windows - CSP如何找到证书的私钥来进行加密操作?

Git:我使用哪个键(默认情况下可能不是)?

java - EAR lib 的类为 WAR 成员抛出 ClassNotFoundException

java - Android - 如何连续运行一个线程,一个接一个

c# - CngKey System.Security.Cryptography.CryptographicException 系统找不到 Azure 上指定的文件

java - 允许 HTTP Post 仅从本地主机访问 Tomcat

linux - 如何将文件从亚马逊 EC2 Linux vps 传输到 Windows 7 家用电脑