如何从未格式化的字符串中获取 public RSA 密钥

How to get public RSA key from unformatted String

我在属性文件中有一个未格式化的 public 键,这意味着它只包含 public 键六进制值:

K_PUB_CCE =  3082010902820100A515281FAC9ABAA8E966DC1B6EC0F1C431674B4E7BCB718955A34211D5CC6BA53F2C93F67C030A970D4E41341949E6BC3F9336287EEA21702FE663C83D4BAFEE2AAA2EEE7A6AFDC423A159D420E42ABDE2792080249C5D6E25367F804333665CAFB79FD5A59D70B9F69159F4EDAD2DA4B434F41D0EC5217808E7D91FF547C83774E4BDE813302E16377156E52CAF02D1E68371D536AA0E7E32DE484FF4863538DCBC69E8D3E3C1F3CECEA9861DA5516A06D3208F6363B86CF66641BE18C4F41ABD7F1B5CDC9BD964914515DDC58F32F49437BD7E89431C8F484BBCEBA86A5FFF74E01D12E6D1D7EBBF6E5DCD7A9134BF27185F4BD347B23007FF366C0009E14F0203010001

如您所见,它有 538 个六边形长。我想要实现的是获得具有此值的 java.security.PublicKey

但是使用这个方法时:

private PublicKey createPublicKey(String stringPublicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
    byte[] bytesKey= Hex.decodeHex(stringPublicKey.toCharArray());
    X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(bytesKey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return  keyFactory.generatePublic(encodedKeySpec);
}

我得到以下异常:

java.security.InvalidKeyException: IOException: algid parse error, not a sequence

我做错了什么?我应该使用任何其他关键规范 class 吗?

将 public 密钥存储为 base64 字符串然后将其转换回来是相当麻烦的(因为还取决于平台,格式可能会有所不同)。使用 KeyStore 文件会容易得多。

如果这不适合您,还有另一种方法。您需要输入密钥(模数)和使用的指数。指数通常是 65537,但也有一些方法可以确定(参见参考资料)。这对我有用:

public static void main(String[] args) {
    try{
        // example key generated via: $ openssl genrsa -out tmp-key.pem 2048
        // modulus and exponent extracted via: $ openssl rsa -text -in tmp-key.pem
        // (modulus 514 hex long)
        String pubModulus = "00e45679a14c6cbd4646bbe90b3c820eb19fe8366822ce2e4beed9d158b9e8863bdc4e3f0fbad31144ef193493dff8619a5aaa7504541c5d97c20cd29c87435eb2e4fbbab8e3b02d82353016c91e971e8d497e1699eeb77a833833617369333c4d0d93cd6f1a9e6090fafd4cbf00b1e0fc6478003ed6e762fb921446c84f0f281117e692a5f76e4b75cbb1252436b3268893195d25344cc3e5d5a52560243d62e5ce8a7bd72a89fce5fbf009435901e274c3cca5eab0f2b2057683ed6e3ed851723adbabb4028a7900ddc46d8c894097c07ab071f6af8fc1c520681e0abd7685f4851d360a7c6d425373da806d356a517ae764093e6999d2cc9305f46a7e1744ed";
        String pubExp = "65537"; // most common exponent is 65537 which encodes to AQAB

        PublicKey key = createPublicKey(pubModulus, pubExp);
        byte[] data = encrypt("Secret Message", key);
        System.out.println(""+data.length); // prints "256" in this example code
    } catch(Exception e) {
        e.printStackTrace();
    }
}

public static PublicKey createPublicKey(String stringPublicKey, String exponentString) throws NoSuchAlgorithmException, InvalidKeySpecException {
    try{
        // for key modulus and exponent value as base64 encoded string from key file
        //BigInteger keyInt = new BigInteger(Base64.getDecoder().decode(stringPublicKey.getBytes("UTF-8")));
        //BigInteger exponentInt = new BigInteger(Base64.getDecoder().decode(exponentString.getBytes("UTF-8")));

        // for key modulus and exponent values as hex and decimal string respectively
        BigInteger keyInt = new BigInteger(stringPublicKey,16); // hex base
        BigInteger exponentInt = new BigInteger(exponentString,10); // decimal base

        RSAPublicKeySpec keySpeck = new RSAPublicKeySpec(keyInt, exponentInt);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return  keyFactory.generatePublic(keySpeck);
    } catch(Exception e) {
        e.printStackTrace();
    }

    return null;
}

public static byte[] encrypt(String message, PublicKey key) {
    try{
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] data = cipher.doFinal(message.getBytes());
        return data;
    } catch(Exception e) {
        e.printStackTrace();
    }

    return new byte[1];
}

编辑:

对不起,我刚刚看到您使用的是十六进制字符串。原始 RSA 格式应该是一些 base64 编码值。由于您已经拥有十六进制值,因此模数的 BigInteger 创建应该不同(请参阅源代码编辑)。 同样如以下评论中所述,十六进制字符串或 Base64 格式不会出现平台问题。此处唯一需要注意的是,在使用 getBytes() 从 String 编码为 Base64 时指定一种格式(例如 UTF-8)。如果未指定格式,将使用平台默认值。

参考文献:

RSA exponent 65537

Convert RSA Hex String to PublicKey

How to find out your exponent

About the hex key length/format

Encoding String to Base64

你拥有的是几乎一个PKCS#1 public key的DER编码的十六进制编码。这与 X509EncodedKeySpec class 处理的 SubjectPublicKeyInfo 不同。我说 almost 因为编码有点问题。模数被编码为负整数,这是错误的。

处理此问题的最简单方法是使用十六进制字符串手动分解模数和指数,如下面的小示例所示。

import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPublicKeySpec;

public class ProcessPKCS1RSAPublicKey {

    public static void main(String[] args) throws Exception {
        String modulusHex = "A515281FAC9ABAA8E966DC1B6EC0F1C431674B4E7BCB718955A34211D5CC6BA53F2C93F67C030A970D4E41341949E6BC3F9336287EEA21702FE663C83D4BAFEE2AAA2EEE7A6AFDC423A159D420E42ABDE2792080249C5D6E25367F804333665CAFB79FD5A59D70B9F69159F4EDAD2DA4B434F41D0EC5217808E7D91FF547C83774E4BDE813302E16377156E52CAF02D1E68371D536AA0E7E32DE484FF4863538DCBC69E8D3E3C1F3CECEA9861DA5516A06D3208F6363B86CF66641BE18C4F41ABD7F1B5CDC9BD964914515DDC58F32F49437BD7E89431C8F484BBCEBA86A5FFF74E01D12E6D1D7EBBF6E5DCD7A9134BF27185F4BD347B23007FF366C0009E14F";
        BigInteger modulus = new BigInteger(modulusHex, 16);
        String exponentHex = "010001";
        BigInteger exponent = new BigInteger(exponentHex, 16);
        RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, exponent);
        KeyFactory keyFac = KeyFactory.getInstance("RSA");
        RSAPublicKey rsaPub = (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
        System.out.println(rsaPub);
    }

}