java - 从十六进制字符串 key 格式生成 RSA 私钥

标签 java openssl rsa hexdump

我有 key.json 数据,其中存储了以下信息:

{
  "privateExponent":"0x74326408a9392dc21ab4297391a8c2152c165ca71a3f2282ded681f2cbf8c999eb27bb17524edf431004fd5c5c4eae82ee9138d5bebd61b80f497f762a8bace0baaee6a374f94b27ee4824ebacbfed15d568f9cc17b369af3f0ad879c1d442a2401c01687d7ea51e64f5e8ca67437d4c591a699604af0adca695761561844527002ae51dd0c5a93217a1c6022c97091761837fb8341a6f85254a29bc2d3e48791a6347701a7743760546530fbe236c9bf90f9994ea428777b065c92dfd1bfa86796f43e1e2a1b47299e52c61620ad4ebe26b9bacec78ca73e66efa9404628a550c29ea59eb9826de5342da7b84bba6bcd50aa0fe267eaa8d113fab76262d4fe9",
  "publicExponent": "0x100010",
  "modulus": "0x00e1de9b838b4b2026b29f03d8fecb916622b25dd89d317d5e79ba2a3e148b2d73278cb1944ba4be4bf87f9ab03f612cb28944bc45086a00a9f87ea489ff0ea866e5d6cf62654065d12967d05836b286d9d55d0fe67faa7b77d8c66346b76b0716946e5a96c64f180e1bc71881534d79eba75582bba448ad648cf93d59c8eeb738ea6bb9a94ffada4ecee846b3aa666ba0fb68c10b39ed65aa067046e970cf19d2a92b787643e54ce09e1c7459475aa6d4b89eb5032dcf7b8b80833f12a5c86cce46f3d2583feccc6243653f75c0412499a2edafddad31f70811bcf81343a49933c992d25efc1e522220ea9da6c5cf80d9ed63ff5c21a1cc7fb537b414e6708957"
}

从 pem 文件中检索 privateExponent、public Exponent 和模数的信息,其中 key 由 openssl 创建:

openssl genrsa 2048 > key.pem

openssl rsa -text

因此,首先我删除开头的“0x”,因为在 Java 中存储十六进制字符串时没有 0x。然后,我想将它们转换为字节数组并从中生成一个 key 。这是我这样做的代码:

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;



/* Json Fomrats:
key.json:
privateExponent: hex-String,
public Exponent: hex-String,
modulus: hex-String


payload.json:
message: String,
sig {
    modulus: hex String,
    publicExponent: hex String,
    signature: String
}

 */

public class Main {

    public static String toHexString(byte[] array) {
        return DatatypeConverter.printHexBinary(array);
    }

    public static byte[] toByteArray(String s) {
        return DatatypeConverter.parseHexBinary(s);
    }

    public static void main(String[] args) {


        JSONParser parser = new JSONParser();
        try {

            Object obj = parser.parse(new FileReader(new File((System.getProperty("user.dir") + "\\src\\com\\company\\key.json"))));
            JSONObject jObj = (JSONObject) obj;
            System.out.println(jObj.get("privateExponent").toString());
            String privKeyS = jObj.get("privateExponent").toString().replace("0x", "");
            System.out.println(privKeyS);


            byte[] privKeyBytes = toByteArray(privKeyS);
            System.out.println(privKeyBytes);
            PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey key = keyFactory.generatePrivate(privKeySpec);


        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }

    }
}

当我运行该问题时,我收到以下错误消息:

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
    at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217)
    at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
    at com.company.Main.main(Main.java:70)
Caused by: java.security.InvalidKeyException: invalid key format

为什么呢?我不明白为什么这种格式不起作用。

最佳答案

您正在尝试加载 PKCS#8 编码 key ,但您需要根据 privateExponent 和模数创建 key

//Convert hex strings to BigInteger
BigInteger privateExponent = new BigInteger(privateExponentHex, 16);
BigInteger modulus = new BigInteger(modulusHex, 16);

//Build the private key
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPrivateKeySpec privateSpec = new RSAPrivateKeySpec(modulus, privateExponent);
PrivateKey privateKey = keyFactory.generatePrivate(privateSpec); 

关于java - 从十六进制字符串 key 格式生成 RSA 私钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46681607/

相关文章:

java - 本地主机上的 SSL 证书不起作用

c - OpenSSL ECB 非 64 位多纯文本

c - 使用 openssl 进行数据加密/解密

java - 从 C# 导出适用于 Java 的 X509EncodedKeySpec 的 RSA 公钥

java - 将属性 'source' 设置为 'org.eclipse.jst.jee.server:GestorContenidoWS' 未找到匹配的属性。尝试所有解决方案

java - 如何使用java解析html列表值

java 模式和匹配器

c++ - AES CBC算法的实现

c# - RSA C# 中的 key 大小没有改变!

python - 减少 Python 中 RSA 解密的时间