Java 中生成的 RSA public 密钥在 php 中无效

RSA public key generated in Java is not valid in php

我正在 Java 中创建一个 RSA 密钥对并想在 PHP 中使用它。 Java代码如下:

public static boolean keyGen() throws NoSuchAlgorithmException, IOException, OperatorCreationException, InvalidKeySpecException {
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");  
    kpGen.initialize(2048, new SecureRandom());  
    KeyPair keyPair = kpGen.generateKeyPair();  

    PublicKey pub = keyPair.getPublic();
    byte[] pubBytes = pub.getEncoded();
    SubjectPublicKeyInfo spkInfo = SubjectPublicKeyInfo.getInstance(pubBytes);
    ASN1Primitive primitive = spkInfo.parsePublicKey();
    byte[] publicKeyPKCS1 = primitive.getEncoded();
    PemObject pemObject = new PemObject("RSA PUBLIC KEY", publicKeyPKCS1);
    StringWriter stringWriter = new StringWriter();
    PemWriter pemWriter = new PemWriter(stringWriter);
    pemWriter.writeObject(pemObject);
    pemWriter.close();
    String pemString = stringWriter.toString();
    FileOutputStream fos2 = new FileOutputStream("pubk.key");  
    fos2.write(pemString.getBytes());  
    fos2.flush();  
    fos2.close();
}

生成的 public 密钥如下所示:

-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAh8cQcRitRdEIzcWDpgDhGTxU4e/4CnFcCi4pEi8Pitme4+9MlVOQ
EtwpiaH54nbxBLZX6m/Z0EETqE9hJm02L8cgvp6/T08atJ9NAayEkN5TFSgdmh3Y
CwGa0ckHlO1lzN3jghUTxLnYEHOvBXVaY1SpDEUlLUi6WKsyklqHK+r6fPa9X1sY
6847VPTQX8ORC13LEzdZrGSR39473HTBhR6SzyTET47AgHPy2Q+FMIvN7DeuX5dK
XtQUlvAjJ7KVQJIXuFEzNvHQfUzjJj+LO2MHX77KbGg6Ytz06CnsWS2f6YKBY3Bg
BQ2zqjE2ON1jDLUcika+2ihEzpfXFGLY9wIDAQAB
-----END RSA PUBLIC KEY-----

我正在使用 PHP 导入保存的密钥文件,如下所示:

 $keyString = file_get_contents($filePath);
 openssl_pkey_get_public($keyString);

当尝试使用 openssl_public_encrypt 加密时,它给我错误

openssl_public_encrypt(): key parameter is not a valid public key

不过,我对 Java脚本生成的密钥文件进行了同样的尝试,效果很好。有帮助吗?

密钥显然需要采用 SubjectPublicKeyInfo 格式,有时称为 "X.509" 格式——但与 X.509 证书不同——只是为了增加一般的混乱。我不是从 documentation 而是从下面的用户评论中获得此信息的。

幸运的是,这需要更少的 Java 代码行来生成,正如根据您的代码改编的这个小代码片段所示:

    PublicKey pub = keyPair.getPublic();
    byte[] pubBytes = pub.getEncoded();
    PemObject pemObject = new PemObject("PUBLIC KEY", pubBytes);
    StringWriter stringWriter = new StringWriter();
    PemWriter pemWriter = new PemWriter(stringWriter);
    pemWriter.writeObject(pemObject);
    pemWriter.close();
    System.out.println(stringWriter.toString());