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?
Related
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.
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());
I am trying to generate a RSAPublicKey from the publickey.pem file but it is throwing me exception .
https://github.com/cerner/cds-hooks-sandbox/blob/master/ecpublickey.pem
Invalid token :::java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
KeyFactory factory = KeyFactory.getInstance("RSA");
PemReader pemReader = new PemReader(new InputStreamReader(new
FileInputStream(filename)));
PemObject pemObject = pemReader.readPemObject();
byte[] content = pemObject.getContent();
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content);
RSAPublicKey publicKey = factory.generatePublic(pubKeySpec);
It works fine if I generate and save my own pem file.
I'm trying to read RSA public key shown below, but I get an exception at line 6: java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: algid parse error, not a sequence
My code:
String rsaPublicKey = rsaPublicKeyString.replace(
"-----BEGIN RSA PUBLIC KEY-----\n", "");
rsaPublicKey = rsaPublicKey.replace("\n-----END RSA PUBLIC KEY-----", "");
byte[] bytes = EncryptionUtils.decodeBase64(rsaPublicKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
pubKey = (RSAPublicKey)keyFactory.generatePublic(keySpec);
RSA public key:
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6
lyDONS789sVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcixlEKzwKENj1Yz/s7daS
an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7a+XYl9sluzHRyVVaTTveB2GazTw
Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+
8hdlLmAjbCVfaigxX0CDqWeR1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n
Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
-----END RSA PUBLIC KEY-----
What am I doing wrong?
UPD:
public static byte[] decodeBase64(String data) throws EncryptionException {
try {
BASE64Decoder decoder = new BASE64Decoder();
return decoder.decodeBuffer(data);
} catch (Exception e) {
throw new EncryptionException(e);
}
}
For me, I was missing the OID in the public key. I had to correct that on the iOS side using help from here: http://blog.wingsofhermes.org/?p=42
Also, my public key didn't have to be casted to an RSAPublicKey, the standard worked just fine:
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
Your problem is caused because your public key is an RSAPublicKey object rather than a SubjectPublicKeyInfo object (see this answer for a good description of the difference). You will need to convert from one to the other before your code will work.
BouncyCastle can do the conversion for you. The following code snippet will work, although I dislike it for two reasons:
It uses a deprecated class PEMReader.
It requires the BouncyCastle provider to be loaded.
Code:
Security.addProvider(new BouncyCastleProvider());
PEMReader reader = new PEMReader(new StringReader(rsaPublicKeyString));
BCRSAPublicKey key = (BCRSAPublicKey) reader.readObject();
bytes[] = key.getEncoded(); // now in SubjectPublicKeyInfo format.
// as before...
With BouncyCastle, there is always many ways to skin a cat. Perhaps someone can find a more elegant solution than the one above?
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;
}