RSA public key generated in Java is not valid in php

独自空忆成欢 提交于 2021-01-27 23:21:04

问题


I'm creating a RSA key pair in Java and want to use it in PHP. Java code is as follows:

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();
}

The generated public key looks like follow:

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

And I'm importing the saved key file using PHP as follows:

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

And when try to encrypt using openssl_public_encrypt it gives me the error

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

However I tried the same with a JavaScript generated key file and it works well. Any help?


回答1:


The key evidently needs to be in SubjectPublicKeyInfo format, sometimes referred to as "X.509" format -- but not the same thing as an X.509 certificate -- just to add to the general sea of confusion. I got this info not from the documentation but from the user comments below.

Fortunately this takes even fewer lines of Java code to produce, as this little code fragment adapted from your code illustrates:

    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());


来源:https://stackoverflow.com/questions/53947613/rsa-public-key-generated-in-java-is-not-valid-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!