I have a PEM Key and I want to get a KeyPair with it and bouncycastle. I found this code which seems good but I have a cast exception.
function loadKey() {
File privateKeyFile = new File(keyPath);
PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
Object object = pemParser.readObject();
KeyPair kp;
if (object instanceof PEMEncryptedKeyPair) {
Logger.info("Encrypted key - we will use provided password");
kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
}
else {
Logger.info("Unencrypted key - no password needed");
kp = converter.getKeyPair((PEMKeyPair) object);
}
return kp;
}
And it returns me :
Unencrypted key - no password needed
org.bouncycastle.asn1.x509.SubjectPublicKeyInfo cannot be cast to org.bouncycastle.openssl.PEMKeyPair
I tried several methods but i didn't succeed.
Thanks to help me :)
If you have a private key that has passphrase you might get this exception. Try removing the passphrase:
openssl rsa -in /path/to/originalkeywithpass.key -out /path/to/newkeywithnopass.key
You can use below code
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
For example:
public PrivateKey getKeyFromClassPath(String filename) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream stream = loader.getResourceAsStream("certificates/" + filename);
if (stream == null) {
throw new CertificateException("Could not read private key from classpath:" + "certificates/" + filename);
}
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
try {
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
return kp.getPrivate();
} catch (IOException ex) {
throw new CertificateException("Could not read private key from classpath", ex);
}
}
Related
I have a String stored in a variable:
-----BEGIN RSA PUBLIC KEY-----
MIGHAoGBANAahj75ZIz9nXqW2H83nGcUao4wNyYZ9Z1kiNTUYQl7ob/RBmDzs5rY
mUahXAg0qyS7+a55eU/csShf5ATGzAXv+DDPcz8HrSTcHMEFpuyYooX6PrIZ07Ma
XtsJ2J4mhlySI5uOZVRDoaFY53MPQx5gud2quDz759IN/0gnDEEVAgED
-----END RSA PUBLIC KEY-----
I generate public key as:
public static PublicKey getFromString(String keystr) throws Exception
{
//String S1= asciiToHex(keystr);
byte[] keyBytes = new sun.misc.BASE64Decoder().decodeBuffer(keystr);
ASN1InputStream in = new ASN1InputStream(keyBytes);
DERObject obj = in.readObject();
RSAPublicKeyStructure pStruct = RSAPublicKeyStructure.getInstance(obj);
RSAPublicKeySpec spec = new RSAPublicKeySpec(pStrcut.getModulus(), pStruct.getPublicExponent());
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
How to generate the PrivateKey using bouncy castle in android
{Edit}
Without using bouncy castle i am generating private key like this:
public static PrivateKey getKey(String mKey){
try{
// Read in the key into a String
StringBuilder pkcs8Lines = new StringBuilder();
BufferedReader rdr = new BufferedReader(new StringReader(mKey));
String line;
while ((line = rdr.readLine()) != null) {
pkcs8Lines.append(line);
}
// Remove the "BEGIN" and "END" lines, as well as any whitespace
String pkcs8Pem = pkcs8Lines.toString();
pkcs8Pem = pkcs8Pem.replace("-----BEGIN RSA PRIVATE KEY-----", "");
pkcs8Pem = pkcs8Pem.replace("-----END RSA PRIVATE KEY-----", "");
pkcs8Pem = pkcs8Pem.replaceAll("\\s+","");
// Base64 decode the result
byte [] pkcs8EncodedBytes = Base64.decode(pkcs8Pem, Base64.DEFAULT);
// extract the private key
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(keySpec);
System.out.println(privKey);
return privKey;
}catch (Exception ex){
ex.printStackTrace();
}
return null;
}
I want to achieve the same using Bouncy Castle
I'm a little confused on why you insist on using bouncycastle, but if you really want to use bouncycastle then the CMS/PKIX library has a nice helper class called PEMParser that will shorten the code needed, e.g:
public static PrivateKey getPemPrivateKey(String mKey) throws Exception {
PEMParser pemParser = new PEMParser(new StringReader(mKey));
final PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();
final byte[] encoded = pemKeyPair.getPrivateKeyInfo().getEncoded();
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(new PKCS8EncodedKeySpec(encoded));
}
In command line I can encrypt and decrypt my file with openssl as following:
Create Keys:
openssl req -x509 -newkey rsa:2048 -keyout myKey.key -out myKey.crt -pubkey
Encrypt:
cat myText.txt | openssl rsautl -encrypt -inkey myKey.crt -pubin >> encryptedtxt.enc
Decrypt:
openssl rsautl -decrypt -inkey myKey.key -in encryptedtxt.enc > decryptedtxt.txt
I followed the this tutorial
public static void main(String[] args) {
String encryptedData = "..\\encryptedtxt.enc";
File encryptedFIle = new File(encryptedData);
try {
byte[] data = Files.readAllBytes(encryptedFIle.toPath());
PrivateKey privateKey = getPrivateKey();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedData = cipher.doFinal(data);
System.out.println(">" + new String(decryptedData));
} catch (Exception e) {
e.printStackTrace();
}
}
private static PrivateKey getPrivateKey() {
String privateKeyFilename = "\\myKey.key";
FileInputStream fis = null;
ObjectInputStream ois = null;
File privateKeyFile = new File(privateKeyFilename);
try {
fis = new FileInputStream(privateKeyFile);
ois = new ObjectInputStream(fis);
BigInteger modulus = (BigInteger) ois.readObject();
BigInteger exponent = (BigInteger) ois.readObject();
RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privateKey = fact.generatePrivate(rsaPrivateKeySpec);
return privateKey;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
When this is run, following issue occurs:
java.io.StreamCorruptedException: invalid stream header: 2D2D2D2D
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:857)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:349)
at Decryptor.getPrivateKey(TestClass.java:38)
at Decryptor.main(TestClass.java:20)
java.security.InvalidKeyException: No installed provider supports this key: (null)
at javax.crypto.Cipher.chooseProvider(Cipher.java:893)
at javax.crypto.Cipher.init(Cipher.java:1249)
at javax.crypto.Cipher.init(Cipher.java:1186)
at Decryptor.main(TestClass.java:22)
Any suggestion please how I can I solve this?
UPDATE:
I modified my getting private key method as following:
private static PrivateKey getPrivateKey() {
String privateKeyFilename = "myKey.key";
FileInputStream fis = null;
ObjectInputStream ois = null;
File privateKeyFile = new File(privateKeyFilename);
try {
String key = readFileAsString(privateKeyFilename);
BASE64Decoder b64 = new BASE64Decoder();
byte[] pkcs8EncodedBytes = b64.decodeBuffer(key);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(keySpec);
System.out.println(privKey);
return privKey;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
But then the following error is thrown:
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : Short read of DER length
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217)
at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
at Decryptor.getPrivateKey(TestClass.java:61)
at Decryptor.main(TestClass.java:19)
Caused by: java.security.InvalidKeyException: IOException : Short read of DER length
at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:351)
at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:356)
at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:91)
at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:75)
at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:316)
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:213)
... 3 more
java.security.InvalidKeyException: No installed provider supports this key: (null)
at javax.crypto.Cipher.chooseProvider(Cipher.java:893)
at javax.crypto.Cipher.init(Cipher.java:1249)
at javax.crypto.Cipher.init(Cipher.java:1186)
at Decryptor.main(TestClass.java:21)
You are trying to read the key using an ObjectInputStream. This class is not meant for general purpose decoding; it only decodes a Java-specific serialization format. The error you are seeing is the ObjectInputStream informing you that the data that you are reading is not a serialized Java object.
The key file generated by OpenSSL is not a Java-serialized object. Instead, it uses PEM encoding. For more information on reading keys from a PEM file, have a look at Decrypting an OpenSSL PEM Encoded RSA private key with Java?
I'm newer to RSA and used BC get SubjectPublicKeyInfo from a public key.
String key = "-----BEGIN RSA PUBLIC KEY-----\n" +
"........\n" +// Multiple lines here
"-----END RSA PUBLIC KEY-----\n";
Security.addProvider(new BouncyCastleProvider());
PEMParser reader = new PEMParser(new StringReader(key));
SubjectPublicKeyInfo subjectPublicKeyInfo = (SubjectPublicKeyInfo) reader.readObject();
And then I want encrypt datas. I found some one use RSAEngine to do it:
AsymmetricKeyParameter aKey = (RSAKeyParameters) PublicKeyFactory.createKey(subjectPublicKeyInfo);
AsymmetricBlockCipher engine = new RSAEngine();
engine.init(false, aKey);
byte[] dataEncrypted = engine.processBlock(data, 0, data.length);
After I run those code, I found the result isn't equal to the expection. So I want to know is there any mistake in my code?
Finally I found my way out.
If anyone is familiar with BouncyCastle, he can point me the low-level mistakes.
Firstly, to encrypt data should init Engine with true at first arg in init function.
Secondly, my public key is start with '-----BEGIN RSA PUBLIC KEY-----'. It's PKCS#1 format RSA public key and should use BouncyCastle to read in, but encrypt data should have padding. So, I shouldn't use RSAEngine directly, use PKCS1Encoding instead.
At last , post my encrypt code and decrypt code:
Encryption:
Security.addProvider(new BouncyCastleProvider());
PEMParser reader = new PEMParser(new StringReader(key));
SubjectPublicKeyInfo subjectPublicKeyInfo = (SubjectPublicKeyInfo) reader.readObject();
RSAKeyParameters rsaKeyParameters = (RSAKeyParameters)
PublicKeyFactory.createKey(subjectPublicKeyInfo);
PKCS1Encoding engine = new PKCS1Encoding(new RSAEngine());
engine.init(true, rsaKeyParameters);
return engine.processBlock(data, 0, data.length);
Decryption:
public static byte[] decryptByPublicKey(String data, String key) throws Exception {
byte[] rawData = Base64.decode(data);
Security.addProvider(new BouncyCastleProvider());
PEMParser reader = new PEMParser(new StringReader(key));
PEMKeyPair pemKeyPair = (PEMKeyPair) reader.readObject();
SubjectPublicKeyInfo publicKeyInfo = pemKeyPair.getPublicKeyInfo();
PrivateKeyInfo privateKeyInfo = pemKeyPair.getPrivateKeyInfo();
RSAKeyParameters rsaKeyParameters = (RSAKeyParameters)
PrivateKeyFactory.createKey(privateKeyInfo);
PKCS1Encoding engine = new PKCS1Encoding(new RSAEngine());
engine.init(false, rsaKeyParameters);
return engine.processBlock(rawData, 0, rawData.length);
}
For encryption , you can use modulus and public exponent to create a key that support by JDK:
Security.addProvider(new BouncyCastleProvider());
PEMParser reader = new PEMParser(new StringReader(key));
PemObject obj = reader.readPemObject();
org.bouncycastle.asn1.pkcs.RSAPublicKey rsaPublicKey = org.bouncycastle.asn1.pkcs.RSAPublicKey.getInstance(obj.getContent());
BigInteger modulus = rsaPublicKey.getModulus();
BigInteger publicExponent = rsaPublicKey.getPublicExponent();
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");//This line should use right padding.For PKCS#1 format RSA key , it should be this.
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
return cipher.doFinal(data);
See Also:Basic RSA example.
I have been trying to serialize the object PKCS10CertificationRequest for a while now. I figured the right way to do it is to create an ASN1Primitive class, send it over the network, then deserialize it. However, there seems to be only serialization into ASN1, but there seems to be no deserialization from ASN1, and I don't want to manually parse and reconstruct the Request. What should I do? My code so far is
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "SC");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
System.out.println("Private: " + kp.getPrivate());
System.out.println("Public: " + kp.getPublic());
X500NameBuilder x500NameBld = new X500NameBuilder(BCStyle.INSTANCE);
x500NameBld.addRDN(BCStyle.C, "AU");
x500NameBld.addRDN(BCStyle.O, "The Legion of the Bouncy Castle");
x500NameBld.addRDN(BCStyle.L, "Melbourne");
x500NameBld.addRDN(BCStyle.ST, "Victoria");
x500NameBld.addRDN(BCStyle.EmailAddress, "feedback-crypto#bouncycastle.org");
X500Name subject = x500NameBld.build();
PKCS10CertificationRequestBuilder requestBuilder = new JcaPKCS10CertificationRequestBuilder(subject, kp.getPublic());
PKCS10CertificationRequest req1 = requestBuilder.build(new JcaContentSignerBuilder("SHA1withRSA").setProvider("SC").build(
kp.getPrivate()));
JcaPKCS10CertificationRequest req2 = new JcaPKCS10CertificationRequest(req1.getEncoded()).setProvider("SC");
//serialization
ByteArrayOutputStream abOut = new ByteArrayOutputStream();
ASN1OutputStream berOut = new ASN1OutputStream(abOut);
berOut.writeObject(req2.toASN1Structure());
byte[] serializedData = abOut.toByteArray();
ASN1Primitive asn1Primitive = ASN1Primitive.fromByteArray(serializedData);
System.out.println("");
System.out.println("" + asn1Primitive.toString());
And the output is
[[0, [[[2.5.4.6, AU]], [[2.5.4.10, The Legion of the Bouncy Castle]], [[2.5.4.7, Melbourne]], [[2.5.4.8, Victoria]], [[1.2.840.113549.1.9.1, feedback-crypto#bouncycastle.org]]], [[1.2.840.113549.1.1.1, NULL], #03818D0030818902818100A...
I don't want to parse this manually. What should I do instead?
Forget about ASN1, it is a mess, and there seems to be no automatic deserialization. However, you can use the JcaPEMWriter and PEMParser classes in BouncyCastle to create a String object to serialize or deserialize the data, and send it over the network.
StringWriter sw = new StringWriter();
JcaPEMWriter pemWriter = new JcaPEMWriter(sw);
pemWriter.writeObject(req2);
pemWriter.close();
PEMParser pemParser = null;
try
{
pemParser = new PEMParser(new StringReader(sw.toString()));
Object parsedObj = pemParser.readObject();
System.out.println("PemParser returned: " + parsedObj);
if (parsedObj instanceof PKCS10CertificationRequest)
{
JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest((PKCS10CertificationRequest)parsedObj);
System.out.println("" + jcaPKCS10CertificationRequest.getPublicKey());
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
if (pemParser != null)
{
pemParser.close();
}
}
EDIT: Although if someone really needs to get elements out of ASN1Encodable object (like an RDN of X500Name, apparently you need the IETFUtils class as per https://stackoverflow.com/a/5527171/2413303 .
I'm new to Cryptography.
I would like to generate RSA key in java and write it to a file. Later I would like to read from that file and get the RSA key back.
Code for key generation and writing to file :
public void generate() throws Exception{
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kpair = kpg.genKeyPair();
byte[] publicKeyBytes = kpair.getPublic().getEncoded();
FileOutputStream fos = new FileOutputStream("publicKey");
fos.write(publicKeyBytes);
fos.close();
}
Code for reading and getting back the RSA public key :
public static Key getKeyFromFile(String fileName) throws Exception{
Key pk = null;
File f = new File(fileName);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int)f.length()];
dis.readFully(keyBytes);
dis.close();
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
pk = kf.generatePublic(spec);
return pk;
}
When I run the program I get the following error :
algid parse error, not a sequence
Cannot figure out what's wrong.