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?
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());
Related
i generated a public key file using puttyGen like this:
Resulting in a file with this content:
---- BEGIN SSH2 PUBLIC KEY ----
Comment: "rsa-key-20200116"
AAAAB3NzaC1yc2EAAAABJQAAAQEA9/jf/WH+pfOHU0j9bVYjaPHp9V1F+Tau9Pwh
Zd30m389u8dCFQqWcAYIIbAFs5eE744bdztMpIC2HbqO9hCa5AAq1U2CD0XzWUFg
H5OC9krVSuhnsU6FAJoS2zz+I4P30cuLY98Kzxt6q8pouT3fIgRAmWaKpkO/ol46
APub5ZdTTTqHwpuzOKEI0iVkd6Lsqrp98kLnwCxUV3zyecZN/YsoRRpQaMbdfCfi
kc0qKjwVRNffLk4aCPB4X0yY/EYaeLmNObCuyHqvAojM5SsoB7xlFVLfoNLtnygj
Akxty2+3MO2rsO+dl++sPMNg3EK8pfT+igB0piR2dG9LpQf9Vw==
---- END SSH2 PUBLIC KEY ----
But trying with no luck at all to load this public key from this method below:
public static PublicKey getPublicKey(String fileName) throws Exception {
FileReader reader = new FileReader(fileName);
PemReader pemReader = new PemReader(reader);
PemObject pemObj = pemReader.readPemObject();
pemReader.close();
X509EncodedKeySpec spec = new X509EncodedKeySpec(pemObj.getContent());
KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
return kf.generatePublic(spec);
}
The PemObject resulting is always null. Followed every tutorial found, somebody help me. PemObject and PemReader are from org.bouncycastle.util.io.pem.*
Am i doing something silly?
I have the following public key, that is stored in the DB (PostgresSQL) as text. It's a String, in java:
-----BEGIN RSA PUBLIC KEY-----
MIICCgKCAgEA1ht0OqZpP7d/05373OE7pB7yCVGNGzkUEuCneyfOzps6iA03NbvI
1ZL0Jpp/N3AW73lGdhaoa3X3JE4GsI/bsToVLQwTKmIOC4yjTvBctmFEoyhhTfxW
s1UHZKl4XZ/7THbRlKHhRaTKyfDAbikkMAxNT/qutLAPjnN1qOwjb1oRq52NP6FJ
KWTTikz4UeOHroX+Xthn2fJSJDlQ4YMdBbgrZVx5JcHKNuPTKRf5gI8QQKMSA9Q9
QJRE5OGp7b6dG14ZmOUnUxb00Mp20LgcaGPcuWU+oFsbQaF6W4G4bdkSZRJJXhSg
d4Q7mahpar94/gnztJmth0GzqTWUYyZIWNqIFoMwuOgeaiDV43zb3uLsRVpRKYYy
esmzcOy/jTScVLRCD8QRyu9B2wgCkNAVztQOXPCOOa4O1LlVQWaecIs4WPhOqDhi
KTBhyVkpC1TrrBkp+QMqMqWll1OyVb6k/7uV0qE/i6rHJtjo5v9bcIgYzswyx9CD
9PKl2Q0L0Jg7TMG+yLDIrLfGeuSeEc4XYJzN7bJcCeiizzu5iU9dQUkrncOrq9jn
Ub2pM/+A+JqIsoPK3IY/pJKqH4JYpGKhO1iPQF6iXIZT1r3ZgJUSQtzSeyYqhkla
2uR2BsbPbDqebCuXm3lAsY5w+dujijcn96PKwYha1LsK5sACHuJ79AMCAwEAAQ==
-----END RSA PUBLIC KEY-----
I don't know how this key has been generated, I'm sorry. I have been told to take this key and verify the signature of another string that I'll call "object". I have been told that the algorithm that I have to use to verify "object" is SHA256withRSA.
So, I have written the following java method to read the key
private PublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException {
publicKey = publicKey.replaceAll("\\n", "");
publicKey = publicKey.replace("-----BEGIN RSA PUBLIC KEY-----", "");
publicKey = publicKey.replace("-----END RSA PUBLIC KEY-----", "");
publicKey = publicKey.trim();
byte[] keyDecoded = Base64.getDecoder().decode(publicKey.getBytes());
X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(keyDecoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey pubKey = kf.generatePublic(publicSpec);
return pubKey;
}
The point is that I get the following exception:
java.security.InvalidKeyException: IOException: algid parse error, not
a sequence
I have read plenty of qustions as mine in stackoverflow. The code written by other users is pretty similar (sometimes identical) to mine. So I definitely don't get why it doesn't work for me. Other developers (workmates) are doing the same in php and it works great, so I would discard the hypothesis of wrong public key. Maybe didn't I understood the process clearly? Do you have any clue, please?
I have also tried to cope with the problem using BouncyCastle library, as suggested here, but I get the same exception. The following is the code I have written:
private static PublicKey getPublicKey(String publicKey)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
Security.addProvider(new BouncyCastleProvider());
PemReader pp = new PemReader(new StringReader(publicKey));
PemObject pem = pp.readPemObject();
byte[] content = pem.getContent();
pp.close();
X509EncodedKeySpec spec = new X509EncodedKeySpec(content);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
You can't load that key using an X509EncodedKeySpec. According to it's JavaDoc documentation it expects the following format:
SubjectPublicKeyInfo ::= SEQUENCE {
algorithm AlgorithmIdentifier,
subjectPublicKey BIT STRING }
Instead your key looks different. I used the data from your post, converted it to hex data and posted it into the online ASN.1 decoder.
The output is this:
SEQUENCE (2 elem)
INTEGER (4096 bit) 873481340827968071893572683200799871431146795599597693981565010037737…
INTEGER 65537
As you may recognize your key does not contain an AlgorithmIdentifier therefore it can not be loaded using X509EncodedKeySpec.
My suggestion would be to use the BouncyCastle library and it's PEMParser class for loading this key:
File pemFile = new File("test.pem");
try (PEMParser pp = new PEMParser(new InputStreamReader(new FileInputStream(pemFile)))) {
SubjectPublicKeyInfo subjPubKeyInfo = (SubjectPublicKeyInfo) pp.readObject();
RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(subjPubKeyInfo);
RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
KeyFactory kf = KeyFactory.getInstance("RSA");
java.security.PublicKey publicKey = kf.generatePublic(rsaSpec);
System.out.println(publicKey);
}
Or you manually convert the key to PKCS#8 format via openssl.
This question already has answers here:
Decrypting an OpenSSL PEM Encoded RSA private key with Java?
(2 answers)
Closed 5 years ago.
Given this .pem file (generated with openssl and encrypted with a password):
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,AC009672952033EB
2wegzxf3MtncXS1CY3c.....
....
....
-----END RSA PRIVATE KEY-----
How do I get a PrivateKey object in Java? I wrote the following code but I cannot find the right way to get a KeySpec:
PrivateKey readFromPem(File keyFile, String password){
PemReader r = new PemReader(new InputStreamReader(new FileInputStream(keyFile)));
PemObject pemObject = r.readPemObject();
byte[] encodedKey = pemObject.getContent();
KeySpec keySpec = ???? // how to get this?
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey key = keyFactory.generatePrivate(keySpec);
return key;
}
I guess I should build a RSAPrivateKeySpec, but I don't know how. I tried the method from this answer and this other answer, but they both result in errors when parsing the byte array.
I'm using BouncyCastle 1.57 (bcprov-jdk15on, bcmail-jdk15on and bcpkix-jdk15on) and Java 7.
You can read the private key using the JcaPEMKeyConverter class.
The code below works for keys with and without a password:
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMDecryptorProvider;
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
// don't forget to add the provider
Security.addProvider(new BouncyCastleProvider());
String password = "your password";
// reads your key file
PEMParser pemParser = new PEMParser(new FileReader(keyFile));
Object object = pemParser.readObject();
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
KeyPair kp;
if (object instanceof PEMEncryptedKeyPair) {
// Encrypted key - we will use provided password
PEMEncryptedKeyPair ckp = (PEMEncryptedKeyPair) object;
// uses the password to decrypt the key
PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());
kp = converter.getKeyPair(ckp.decryptKeyPair(decProv));
} else {
// Unencrypted key - no password needed
PEMKeyPair ukp = (PEMKeyPair) object;
kp = converter.getKeyPair(ukp);
}
// RSA
KeyFactory keyFac = KeyFactory.getInstance("RSA");
RSAPrivateCrtKeySpec privateKey = keyFac.getKeySpec(kp.getPrivate(), RSAPrivateCrtKeySpec.class);
System.out.println(privateKey.getClass());
The privateKey's class will be java.security.spec.RSAPrivateCrtKeySpec (which extends RSAPrivateKeySpec).
Use Bouncy Castle's bcpkix dependency which knows how to handle OpenSSL keys.
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk14</artifactId>
<version>1.57</version>
</dependency>
and try it like this:
private PrivateKey readFromPem(File keyFile, String password) throws IOException {
Security.addProvider(new BouncyCastleProvider());
PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(keyFile)));
PEMEncryptedKeyPair encryptedKeyPair = (PEMEncryptedKeyPair) pemParser.readObject();
PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());
PEMKeyPair pemKeyPair = encryptedKeyPair.decryptKeyPair(decryptorProvider);
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
return converter.getPrivateKey(pemKeyPair.getPrivateKeyInfo());
}
I have generated a private key and encrypted it with a password. Now I want to load it to EncryptedPrivateKeyInfo, so that I can construct and export it into a PEM format file. Below is the code I use,
final CertAndKeyGen keypair = new CertAndKeyGen("RSA", "SHA1WithRSA", null);
final X500Name x500Name =
new X500Name("IN", "AP", "HYD", "TEST", "TEST_ORG", "test#xyz.com");
keypair.generate(1024);
final PrivateKey privKey = keypair.getPrivateKey();
final X509Certificate[] chain = new X509Certificate[1];
long validity = 123;
chain[0] = keypair.getSelfCertificate(x500Name, new Date(),
validity * 24 * 60 * 60);
Key key = new SecretKeySpec(password.getBytes(), ALGO);
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(privKey.getEncoded());
AlgorithmParameters params = AlgorithmParameters.getInstance("DES");
params.init(encVal); // <--- exception thrown here
EncryptedPrivateKeyInfo encinfo = new EncryptedPrivateKeyInfo(params, encVal);
// displaying encrypting value
String encryptedValue = Base64.encodeBase64String(encinfo.getEncoded());
System.out.println(encryptedValue);
But while executing the above code, I get the below exception
java.io.IOException: DER input not an octet string
at sun.security.util.DerInputStream.getOctetString(DerInputStream.java:233)
at com.sun.crypto.provider.SunJCE_t.a(DashoA13*..)
at com.sun.crypto.provider.DESParameters.engineInit(DashoA13*..)
at java.security.AlgorithmParameters.init(AlgorithmParameters.java:260)
in the line params.init(encVal);. I don't get what's going wrong from the exception. Any help or suggestion will be really appreciated. Thanks in advance.
A PKCS #8 file containing an encrypted private key has the following ASN.1 structure:
EncryptedPrivateKeyInfo ::= SEQUENCE {
encryptionAlgorithm EncryptionAlgorithmIdentifier,
encryptedData EncryptedData }
Notice how the encrypted data is only part of the total data package. You need to include this data in a sequence along with the encryption algorithm identifier. Your code above produces only the encryptedData part.
I would suggest you consider using BouncyCastle. It looks like they may have improved support for PKCS#8 recently. Here's some sample code:
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = generator.generateKeyPair();
final PrivateKey privKey = keyPair.getPrivate();
JceOpenSSLPKCS8EncryptorBuilder builder =
new JceOpenSSLPKCS8EncryptorBuilder(PKCS8Generator.PBE_SHA1_3DES);
builder.setIterationCount(10000);
builder.setPasssword("Hello, World!".toCharArray());
OutputEncryptor outputEncryptor = builder.build();
PKCS8Generator pkcs8Generator =
new JcaPKCS8Generator(privKey, outputEncryptor);
try (PemWriter writer = new PemWriter(new PrintWriter(System.out))) {
writer.writeObject(pkcs8Generator);
}
This will output an encrypted private key:
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIICrjAoBgoqhkiG9w0BDAEDMBoEFM1kXgdc0vzEhCwQG5G2wAaSA7POAgInEASC
AoAkBPjKkNVpt9O9+Q63WMscX0eEiGyD6/kFwI+ZgH4/s98uKDHxWTB0fQ+HA+Iy
gQC1b+QhT2HVR0DIB6lfhou4FrcJXBAqf4h0ybkfmE4xTfVQcCpgKm4uUC/FYjks
dgTMajN9NHL06nUjd/0uVsM2bzbJHXlDmPRB0LdfvuxzcGN0Vvn13IJrjRnGwTGR
nv6ZyE3gbjCRanINhMtCDMtg9Ydm7+DHC53YOeqbbhgO9/aJHpRzX/H6zLYp/oa0
GpHM6NzsTfABS8QyqR+EaoFad/XHvC9nKUDqm8LVjmKdlXrLDmpHQ4kxZqMIbijE
/Pu2IfHB0jYYa93F2i0fKkIaeve4oo3/izBn0amXVnsPMnkyrIoUUaLzI/gb/419
vp+1kmAKsEFCRIDQlDCiR9CyuePOaR0d7EckVMDU0uR9MXYAV73Y3VRXe1votrQ/
5Wi8ueio9TBDYj9wYYoYmRpz454HqJ/71k0xr5IJugJIJkUzNN9VkjK9rhgT0Vz5
wY/E1yZZepqCR1xrYgDuu/n4t63EERMo+BgkpKBMnWliU3QdQT2r4qBnma+c9lq8
IWb3y3Phl4LsX3DnLed1rUIOcQKiN2T9/yl+7eEtk8APkKuLK5DDDytgAcOQ1MIF
7Ie2939OG1c3mAwrdeOk20zf0SSbpX17MDmUoMwKsP9u8bqHahNoucjtuVSRtjSe
94xntc0fHkiIueApffxjErJOd2pmjGxJ7D2lkjV4G3AEg3vqFXk6E8nPIqIZL4qI
9KzmAFv88+QDIVTM5fheIOxZpeBkXtq2e19gCijiysqLDWL2CLuN4LVzhKCkJF6x
QGN1FcLk95ikvhI/LEn6qrih
-----END ENCRYPTED PRIVATE KEY-----
I have to read pem key files to get RSA Public key,and then use them to encrypt.
I can do this using openssl and convert pem file to der file.
and then load my key using X509EncodedKeySpec and PKCS8EncodedKeySpec.
But I don't want to do this because pem is the user key exchange format.
user can register it's own key can like this :
--BEGIN PUBLIC KEY-- MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgGi0/vKrSIIQMOm4atiw+2s8tSojOKHsWJU3oPTm
b1a5UQIH7CM3NgtLvUF5DqhsP2jTqgYSsZSl+W2RtqCFTavZTWvmc0UsuK8tTzvnCXETsnpjeL13
Hul9JIpxZVej7b6KxgyxFAhuz2AGscvCXnepElkVh7oGOqkUKL7gZSD7AgMBAAE=
--END PUBLIC KEY--
and this key is store in a database in this format...
Here is the code I have tried..
File pubKeyFile=new File("D:/public_key.pem");
DataInputStream dis = new DataInputStream(new FileInputStream(pubKeyFile));
byte[] pubKeyBytes = new byte[(int)pubKeyFile.length()];
dis.readFully(pubKeyBytes);
dis.close();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes);
RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
I am getting exception as
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
As I am completely new to encryption concepts can anyone please help me to solve this exception?
Many thanks.
With bouncycastle, it would be done this way:
CertificateFactory cf = CertificateFactory.getInstance("X509", "BC");
InputStream is = new FileInputStream("D:/public_key.pem");
X509Certificate certificate = (X509Certificate) cf.generateCertificate(is);
is.close();
RSAPublicKey pubKey = (RSAPublicKey)certificate.getPublicKey();
You were almost there, with the standard provider. You just need to strip the header and footer lines:
List<String> lines = Files.readAllLines(Paths.get(path), StandardCharsets.US_ASCII);
if (lines.size() < 2)
throw new IllegalArgumentException("Insufficient input");
if (!lines.remove(0).startsWith("--"))
throw new IllegalArgumentException("Expected header");
if (!lines.remove(lines.size() - 1).startsWith("--"))
throw new IllegalArgumentException("Expected footer");
byte[] raw = Base64.getDecoder().decode(String.join("", lines));
KeyFactory factory = KeyFactory.getInstance("RSA");
PublicKey pub = factory.generatePublic(new X509EncodedKeySpec(raw));
try using bouncycastele's PemReader .
PublicKey getPublicKey(String pubKeyStr) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
PemObject pem = new PemReader(new StringReader(pubKeyStr)).readPemObject();
byte[] pubKeyBytes = pem.getContent();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes);
RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
return pubKey;
}