I have this issue where I dont know how to read my public key file, I have looked for a while now for solutions but they tend to not answer my question in my case. I have a program which generates a public and a private key, I have another method that writes them down in there own files respectively. This may sound silly but I really dont know how I can read the key from a file. This is needed as I want to do asymetrec encryption and so will be transphereing key files around. I will link my code below, any help is much appreaciated :)
If you need anymore detail to my explanation then feel free to ask.
Thanks!
Key Generation and storage methods:
public class Encryption {
public static PrivateKey privateKey;
public static PublicKey publicKey;
public void KeyGeneration() throws NoSuchAlgorithmException{
KeyPairGenerator Generator = KeyPairGenerator.getInstance("RSA"); // Creat the Generator object with RSA
Generator.initialize(1024); // Set the generator to make the 2048 bit key
KeyPair Pair = Generator.genKeyPair(); // Generate the key pair
publicKey = Pair.getPublic(); // Set the Public Key
privateKey = Pair.getPrivate(); // Set the private Key
System.out.println(Base64.getEncoder().encodeToString(publicKey.getEncoded()));
System.out.println(Base64.getEncoder().encodeToString(privateKey.getEncoded()));
}
public void writeToFile(String filePath, byte[] key) throws IOException{
File fileToWriteto = new File(filePath);
fileToWriteto.getParentFile().mkdirs();
FileOutputStream FoutputStream = new FileOutputStream(fileToWriteto);
FoutputStream.write(key);
FoutputStream.flush();
FoutputStream.close();
}
}
The easiest way to save and load RSA key files is by using the encoded version. The below code is saving a private and a public key to a file in encoded form.
The simple output:
Save and load RSA Keys encoded
private key equals: true
public key equals: true
Warning: please note that the following code has no exception handling and is for educational purpose only.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
public class SaveLoadRsaKeysSo {
public static void main(String[] args) throws GeneralSecurityException, IOException {
System.out.println("Save and load RSA Keys encoded");
KeyPairGenerator rsaGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom random = new SecureRandom();
rsaGenerator.initialize(2048, random);
KeyPair rsaKeyPair = rsaGenerator.generateKeyPair();
PublicKey rsaPublicKey = rsaKeyPair.getPublic();
PrivateKey rsaPrivateKey = rsaKeyPair.getPrivate();
// save private & public key
Files.write(Paths.get("rsaPrivateKey.encoded"), rsaPrivateKey.getEncoded());
Files.write(Paths.get("rsaPublicKey.encoded"), rsaPublicKey.getEncoded());
// load private & public key
byte[] privateKeyBytesLoad = Files.readAllBytes(Paths.get("rsaPrivateKey.encoded"));
PrivateKey privateKeyLoad = getPrivateKeyFromEncoded(privateKeyBytesLoad);
byte[] publicKeyBytesLoad = Files.readAllBytes(Paths.get("rsaPublicKey.encoded"));
PublicKey publicKeyLoad = getPublicKeyFromEncoded(publicKeyBytesLoad);
System.out.println("private key equals: " + Arrays.equals(rsaPrivateKey.getEncoded(), privateKeyLoad.getEncoded()));
System.out.println("public key equals: " + Arrays.equals(rsaPublicKey.getEncoded(), publicKeyLoad.getEncoded()));
}
public static PrivateKey getPrivateKeyFromEncoded(byte[] key) throws GeneralSecurityException {
KeyFactory kf = KeyFactory.getInstance("RSA");
return (PrivateKey) kf.generatePrivate(new PKCS8EncodedKeySpec(key));
}
public static PublicKey getPublicKeyFromEncoded(byte[] key) throws GeneralSecurityException {
KeyFactory kf = KeyFactory.getInstance("RSA");
return (PublicKey) kf.generatePublic(new X509EncodedKeySpec(key));
}
}
Related
I want to encrypt my password in angular side before sending it to Springboot API. My idea is to do:-
Generate public key and private key in java
Do a base64 encoding on both public key and private key
Use encoded public key in node (angular) side, this will be used for encryption
Use encoded private key in springboot rest api, this will be used for decryption
Below is my java code which generates, encrypts and decrypts password
RSAKeyPairGenerator.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
public class RSAKeyPairGenerator {
private static String privateKeyString = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALyR1WRqVBuvdmXmgrcZ4VMY4hIFTYt63NGEN9atlgnngNliMasvzBofnjRtk5mukezUKujtON6mPnAjKJoEDdiaw3Rk0hKvgW5MszyUBE5bLThexVLbi+nQYSf2GSvd0fjdZn6KjhgVOdbYe+JduU/iPD3/Ti5p+w3MewgZpy2RAgMBAAECgYAqWdqCXfsb6LF/u2C6PN7Faf5EK9q5q9NyXu6nkX70JIFk0U/0cZy2dUlz3vRafMGbXh9xBu5R2yaEyvCwfp6ZF26A8MbS/IaI53LMKmyclhES2f3tZLKUPkg6fntz+e6e/6oSDdQPHP3J2QrpuwzyW+UZJQmmYYj7f9sq/+dawQJBAOnkHWkLuIZNIgLzV0TuHA6fcOXrqrSlS1/Q0qLyaQEZOObocXDvWaCSP+8RXiqZSwAnMJbrGHQA5ULXLWI4GjkCQQDOZP6bfn2VV3m8JSlYL9Uz4TrRYb8Qe3/mohhMsyDB7Ua/6d9BV7JZgbYiXP0utobKVWLxD49OFMkgEs20qY4ZAkB4dJsQ9pBZ2m+hxWE0hsy8WzDxuKV504c2GX3hnaamgi7j/OIvn5UxNSDoJrGwjrIpqgVENF+rnqpz+g3Nf8dBAkBV/op+6yMUGFBmbe1eCwAAD7XcC6f6DBrsU1lgi7n4Uw6JY75bkViEJqFmi+wJjI94uj7xRZRl6g8qx+rhfUvxAkEArD1we6ZLTWz73D8z+4Boj7Su7b5LhfgvXVL5V4Zdog3X58pHK+dYppapDh5KjZZdor+y/6uz1PqIs2dmFy/xtQ==";
private static String publicKeyString = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8kdVkalQbr3Zl5oK3GeFTGOISBU2LetzRhDfWrZYJ54DZYjGrL8waH540bZOZrpHs1Cro7Tjepj5wIyiaBA3YmsN0ZNISr4FuTLM8lAROWy04XsVS24vp0GEn9hkr3dH43WZ+io4YFTnW2HviXblP4jw9/04uafsNzHsIGactkQIDAQAB";
private static PrivateKey privateKey;
private static PublicKey publicKey;
public void generateKeys() throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair pair = keyGen.generateKeyPair();
RSAKeyPairGenerator.privateKey = pair.getPrivate();
RSAKeyPairGenerator.publicKey = pair.getPublic();
}
public void readKeys() throws NoSuchAlgorithmException, InvalidKeySpecException {
KeyFactory kf = KeyFactory.getInstance("RSA");
byte [] encoded = Base64.getDecoder().decode(privateKeyString);
PKCS8EncodedKeySpec keySpec1 = new PKCS8EncodedKeySpec(encoded);
RSAKeyPairGenerator.privateKey = kf.generatePrivate(keySpec1);
encoded = Base64.getDecoder().decode(publicKeyString);
X509EncodedKeySpec keySpec2 = new X509EncodedKeySpec(encoded);
RSAKeyPairGenerator.publicKey = kf.generatePublic(keySpec2);
}
public static void main(String[] args) throws NoSuchAlgorithmException, IOException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException {
RSAKeyPairGenerator keyPairGenerator = new RSAKeyPairGenerator();
// Next line is for testing with encrypted text generated by nodejs code with genrated keys
// keyPairGenerator.generateKeys();
keyPairGenerator.readKeys();
System.out.println("-----Private----------");
System.out.println(Base64.getEncoder().encodeToString(privateKey.getEncoded()));
System.out.println("Encoding : "+ privateKey.getFormat());
System.out.println("----------------------");
System.out.println("-----Public----------");
System.out.println(Base64.getEncoder().encodeToString(publicKey.getEncoded()));
System.out.println("Encoding : "+ publicKey.getFormat());
System.out.println("----------------------");
String secretMessage = "Test";
System.out.println(secretMessage);
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] secretMessageBytes = secretMessage.getBytes(StandardCharsets.UTF_8);
byte[] encryptedMessageBytes = encryptCipher.doFinal(secretMessageBytes);
// Next lines are for testing decryption with encrypted text generated by nodejs code with generated keys
// byte[] encryptedMessageBytes = "B��u���<⌂�lǚm0�W������1�%EN�7��‼��l��l�<�����k;�������GĦ9D8��Z��I�Oɺ♫��→P'�§�{k�Ɋ+-}?��rZ".getBytes();
// byte[] encryptedMessageBytes = Base64.getDecoder().decode("woboAUytDXJLlKm7zbqNdxVORG+kio9kZxvMPOHruQfxwNEx7SVFTsw3oeETqbRs4NZskjzO2Nzjyms73vv758Dcy0fEpjlEOKmrWuG62knOT8m6DqGDGlAn1hXpe2u6yYorLX0/6fhyWg1C/JR1sbaKPH/Xt+Fsx5ptMONX0uw=");
System.out.println(new String(encryptedMessageBytes));
Cipher decryptCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedMessageBytes = decryptCipher.doFinal(encryptedMessageBytes);
String decryptedMessage = new String(decryptedMessageBytes, StandardCharsets.UTF_8);
System.out.println(decryptedMessage);
}
}
This gives me following output
-----Private----------
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMv+t+D6/7ZY6m+CjD97NB989P2YjmGcE2yHUokyjmxVi/SxIu9MboiVNewR+mFjTFYPGgMWHz1/XeVGlinjN/5+0fdiO/JEvEUilFmkkIF3My11I09b9NZ9RJmpCNCbqOg7NSt6VD8IC/w19N25xwcofc3qbgfEjKSs0CgxfahrAgMBAAECgYEAiyLlEBKiryDeZchJGFNULdXw07dmBbWKmg+CgAl3kvSWTQM0rLsY+Rese6OXfy1XN6t9NnW0QSHKTUNj0JYl7btKEblVHERbjwavUe83tcNIc3o0xrGoBAzma14ZicPYm70JWixTO778lm5AXKl504+oOQyVYmfgXcevPXwdIkECQQDvO3DBuu6wp5nbwR4t0736HOH9jVIjJOS8oABUARDhNt1fkb8uEptDr5EomVRMqarJMAjSMpYxrUCpvgtf4nZ5AkEA2ksDr8pbbFvZPaAe0F43LmJtFM3PvCz87S93p20YjwVMmGV17sJ5t7a26HtubgRLEWq4z6rxq2oXPv4y1lstAwJAbj9cVUtKWIrEcutqdwAPmsXYt7p60ctcxjiOLihXmRJprnNCQX89olG0eZs/qBzAofrK9eNuJ/KJzC/SmhuJMQJAAz9gc6oQCCGprrgGHVV5frAqLUgOkh8dOC4fmpcN6XrLs+y2f3HXO7t1JypG704TC9RJoZVKeSFf7Sj8+qFqnwJBALRiQc9SG5Ht5TLo12W4l3bRaxpbo597BgKRjz3hqiySdqjZA9Qe84qmEKveZ9eWehbfqwzKmCbW43I1ZEFZ95o=
Encoding : PKCS#8
----------------------
-----Public----------
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDL/rfg+v+2WOpvgow/ezQffPT9mI5hnBNsh1KJMo5sVYv0sSLvTG6IlTXsEfphY0xWDxoDFh89f13lRpYp4zf+ftH3YjvyRLxFIpRZpJCBdzMtdSNPW/TWfUSZqQjQm6joOzUrelQ/CAv8NfTduccHKH3N6m4HxIykrNAoMX2oawIDAQAB
Encoding : X.509
----------------------
Test
�N::�`��\A���ƈ�~��5s���
�0�I�C�uƹx2�Z&Kں�"ьC�$
q��K���h�^<�5�E�Ɨ0B�͒Z�{��EDbDH�.��#:�e��h~j���������q�c��R�
Test
In the Nodejs side I am using the above public to encrypt my text.
index.js
const crypto = require("crypto");
var pubkey = "-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDL/rfg+v+2WOpvgow/ezQffPT9mI5hnBNsh1KJMo5sVYv0sSLvTG6IlTXsEfphY0xWDxoDFh89f13lRpYp4zf+ftH3YjvyRLxFIpRZpJCBdzMtdSNPW/TWfUSZqQjQm6joOzUrelQ/CAv8NfTduccHKH3N6m4HxIykrNAoMX2oawIDAQAB\n-----END PUBLIC KEY-----";
var plaintext = "Test"
var buffer = new Buffer.from(plaintext, "utf8");
var enc = crypto.publicEncrypt(pubkey, buffer);
var bs64 = enc.toString('base64');
console.log(enc.toString());
console.log(enc.toString('base64'));
this gives me following output
B��u���<⌂�lǚm0�W������1�%EN�7��‼��l��l�<�����k;�������GĦ9D8��Z��I�Oɺ♫��→P'�§�{k�Ɋ+-}?��rZ
woboAUytDXJLlKm7zbqNdxVORG+kio9kZxvMPOHruQfxwNEx7SVFTsw3oeETqbRs4NZskjzO2Nzjyms73vv758Dcy0fEpjlEOKmrWuG62knOT8m6DqGDGlAn1hXpe2u6yYorLX0/6fhyWg1C/JR1sbaKPH/Xt+Fsx5ptMONX0uw=
Now I tried using both the strings in java side for decryption.
When I try decoding the string, it gives me following error
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Data must not be longer than 128 bytes
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:346)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:391)
at javax.crypto.Cipher.doFinal(Cipher.java:2168)
at com.mindtree.starr.wsr.RSAKeyPairGenerator.main(RSAKeyPairGenerator.java:90)
And, when I try decoding the base64 string, it gie me following error
Exception in thread "main" javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:379)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:290)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:365)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:391)
at javax.crypto.Cipher.doFinal(Cipher.java:2168)
at com.mindtree.starr.wsr.RSAKeyPairGenerator.main(RSAKeyPairGenerator.java:90)
What am I doing wrong?
The problem was clearly described in the first comment and the solution is in second comment.
Correct transformation string for Cipher instance that worked for me is RSA/ECB/OAEPWithSHA-1AndMGF1Padding
So below instantiation for decryption Cipher works perfectly.
Cipher decryptCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
I am trying to generate a shared key from Alice and Bob. I used a key generator to get public and private keys for Bob and Alice. Then, I generated a secret key using AES. What I am supposed to do is encrypt the secret key then decrypt it, and it should be the same as the original secret key. However, my code is giving me an exception that says "decryption error". And I cannot figure out why. Can anyone help me? Thank you!
Also, decodeBytes and generateSharedKey are supposed to be equal and I was having trouble with that as well.
import java.security.*;
import java.util.UUID;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class rsa {
static SecretKey sharedKey = null;
public static void main(String[] args) throws NoSuchAlgorithmException,
NoSuchProviderException, InvalidKeyException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException {
//Generates Key Pair -> a private and public key for both Alice and
Bob
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
//Alice's key pair
KeyPair aliceKey = keyGen.genKeyPair();
PublicKey pubAlice = aliceKey.getPublic(); //alice's public key
PrivateKey privAlice = aliceKey.getPrivate();//alice's private key
//Bob's key pair
KeyPair bobKey = keyGen.genKeyPair();
PublicKey pubBob = bobKey.getPublic(); //bob's public key
PrivateKey privBob = bobKey.getPrivate();// bob's private key
//Generates a random key and encrypt with Bob's public Key
System.out.println(generateSharedKey());
byte[] keyEncrypted = encrypt(sharedKey, pubBob);
byte[] decodeBytes = decrypt(sharedKey, privBob);
System.out.println(decodeBytes);
}
public static SecretKey generateSharedKey() throws
NoSuchAlgorithmException{
KeyGenerator sharedKeyGen = KeyGenerator.getInstance("AES");
sharedKey = sharedKeyGen.generateKey();
return sharedKey;
}
public static byte[] encrypt(SecretKey sharedKey, PublicKey pubKey)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
//System.out.println(inputBytes);
return cipher.doFinal(generateSharedKey().getEncoded());
}
public static byte[] decrypt(SecretKey sharedKey, PrivateKey privKey)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privKey);
return cipher.doFinal(generateSharedKey().getEncoded());
}
}
Please carefully read your code before posting... You are generating a new shared key and then trying to decrypt that in your decrypt method...
You should be passing in a byte[] to decrypt and returning a SecretKey, not the other way around.
I am new to Android and i am working on a client server based application.Here i need to use RSA algorithm for Encryption/Decryption.
The scenario is:
1.Server has to create a Private/Public key pair (PHP) and send Public key to Client(Android Application)
2.The client should encrypt the data using that Public key and send to server
3.Now server has to decrypt using Private Key.
In PHP, i used 'PhpSecLib' to create key pair.
This is the coding :
Server.php:
<?PHP
include 'Crypt/RSA.php';
$rsa = new Crypt_RSA();
extract($rsa->createKey(1024));
echo $publickey;
?>
Generated Public Key :
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLz4yAo1FTOLc6nijBCTv5iVnW
F6MxCeM5+RxY+29AXcpMWhlM9oES3ESIfWw6OzrrENDyqwY+kVzCj2bWYnEAyJXs
WOpvqT2XSCPplwZOnQQGm+DnAYJXEeOfgU5DI63fwdiGv4M2ph1VMMe6684sBZu1
HhJHuhsX2eibBR0/lQIDAQAB
Now in Java, i successfully received this public key and stored in a String.
Coding:
protected String doInBackground(Void... params)
{
try
{
URL url=new URL("http://10.0.2.2/Samples/Server.php");
URLConnection con=url.openConnection();
con.setDoOutput(true);
BufferedReader ip=new BufferedReader(new InputStreamReader(con.getInputStream()));
String tmp,res="";
while((tmp=ip.readLine())!=null)
{
res+=tmp;
}
return res; //res contains the public key
}
catch(Exception e)
{
return new String("Exception : "+e.getMessage());
}
}
I am using Bouncy castle provider (bcprov-jdk15on-151) in java.
Now i have no idea about how to convert this string into RSA public key.
Pls suggest some code snippets? and if the code needs improvements and corrections, pls correct it.
Thanks...
Supposing that you download your key correctly, you can use your key in base 64 encoding to generate a java.security.PublicKey with the follow code:
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
public class ParseRsaPublicKey {
public static void main(String[] args) throws Exception {
String yourKeyB64 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLz4yAo1FTOLc6nijBCTv5iVnW\n"+
"F6MxCeM5+RxY+29AXcpMWhlM9oES3ESIfWw6OzrrENDyqwY+kVzCj2bWYnEAyJXs\n"+
"WOpvqT2XSCPplwZOnQQGm+DnAYJXEeOfgU5DI63fwdiGv4M2ph1VMMe6684sBZu1\n"+
"HhJHuhsX2eibBR0/lQIDAQAB";
// create the key factory
KeyFactory kFactory = KeyFactory.getInstance("RSA", new BouncyCastleProvider());
// decode base64 of your key
byte yourKey[] = Base64.decode(yourKeyB64);
// generate the public key
X509EncodedKeySpec spec = new X509EncodedKeySpec(yourKey);
PublicKey publicKey = (PublicKey) kFactory.generatePublic(spec);
// now you can for example cipher some data with your key
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherData = cipher.doFinal("someData".getBytes());
System.out.println(new String(cipherData));
}
}
Hope this helps,
I have a RSA Key and a X.509 Certificate which I use for SSL connections.
The key and certificate are stored in files in PEM format (generated by OpenSSL) and used in an Apache HTTP server environment.
Is there an easy way to validate if the key matches the certificate using only Java code (without executing the openssl binary and parsing the output), for example by using Java security and/or Bouncycastle library methods?
The following code compares the SHA-1 over the modulus within the public and private key. The modulus should be unique for each pair (unless you key pair generation mechanism or random generator is broken of course).
Note that the following code requires the key to be in unencrypted PKCS#8 format. It may be better to use PKCS#12 instead and load the binary PKCS#12 file in a KeyStore (providing the password).
openssl pkcs8 -topk8 -in key.pem -out keypk8.pem -nocrypt
And finally the Java code:
import static org.bouncycastle.util.encoders.Hex.toHexString;
import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
public class CompareCertAndKey {
/**
* Checks if the certificate and RSA private key match.
*
* #param args the path to the certificate file in args[0] and that of the private key in args[1]
*/
public static void main(String[] args) {
try {
final PemReader certReader = new PemReader(new FileReader(args[0]));
final PemObject certAsPemObject = certReader.readPemObject();
if (!certAsPemObject.getType().equalsIgnoreCase("CERTIFICATE")) {
throw new IllegalArgumentException("Certificate file does not contain a certificate but a " + certAsPemObject.getType());
}
final byte[] x509Data = certAsPemObject.getContent();
final CertificateFactory fact = CertificateFactory.getInstance("X509");
final Certificate cert = fact.generateCertificate(new ByteArrayInputStream(x509Data));
if (!(cert instanceof X509Certificate)) {
throw new IllegalArgumentException("Certificate file does not contain an X509 certificate");
}
final PublicKey publicKey = cert.getPublicKey();
if (!(publicKey instanceof RSAPublicKey)) {
throw new IllegalArgumentException("Certificate file does not contain an RSA public key but a " + publicKey.getClass().getName());
}
final RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
final byte[] certModulusData = rsaPublicKey.getModulus().toByteArray();
final MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
final byte[] certID = sha1.digest(certModulusData);
final String certIDinHex = toHexString(certID);
final PemReader keyReader = new PemReader(new FileReader(args[1]));
final PemObject keyAsPemObject = keyReader.readPemObject();
if (!keyAsPemObject.getType().equalsIgnoreCase("PRIVATE KEY")) {
throw new IllegalArgumentException("Key file does not contain a private key but a " + keyAsPemObject.getType());
}
final byte[] privateKeyData = keyAsPemObject.getContent();
final KeyFactory keyFact = KeyFactory.getInstance("RSA");
final KeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyData);
final PrivateKey privateKey = keyFact.generatePrivate(keySpec);
if (!(privateKey instanceof RSAPrivateKey)) {
throw new IllegalArgumentException("Key file does not contain an X509 encoded private key");
}
final RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
final byte[] keyModulusData = rsaPrivateKey.getModulus().toByteArray();
final byte[] keyID = sha1.digest(keyModulusData);
final String keyIDinHex = toHexString(keyID);
System.out.println(args[0] + " : " + certIDinHex);
System.out.println(args[1] + " : " + keyIDinHex);
if (certIDinHex.equalsIgnoreCase(keyIDinHex)) {
System.out.println("Match");
System.exit(0);
} else {
System.out.println("No match");
System.exit(-1);
}
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-2);
}
}
}
Thank you very much for the above code snippet. Its working for me with bouncycastle version 1.51
<bcprov-jdk15on-version>1.51</bcprov-jdk15on-version>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>${bcprov-jdk15on-version}</version>
</dependency>
Many Thanks for your code snippet.
I'm trying to read a private key from a .pem file in PKCS#8 format, the problem I've faced is that these kind of files have this header
-----BEGIN PRIVATE KEY-----
so there is no information about the algorithm used to instantiate the key, my question is:
is there a method to know the algorithm without decoding the key (which is base64) and see the algorithm modifier, also if there is a way to know the length of the key..
help is appreciated
Using Bouncy Castle and modifying the code from this answer, I came up with this to get your answers.
Note: This code will only work with non-encrypted private keys.
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.Security;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.jcajce.provider.asymmetric.dsa.BCDSAPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.rsa.BCRSAPrivateKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
public class PemKeyInfo
{
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException
{
Security.addProvider(new BouncyCastleProvider());
String privateKeyFileName = "C:\\privkeypk8.pem";
File privateKeyFile = new File(privateKeyFileName); // private key file in PEM format
PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
Object object = pemParser.readObject();
pemParser.close();
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
PrivateKey privkey = null;
if (object instanceof PrivateKeyInfo)
{
privkey = converter.getPrivateKey((PrivateKeyInfo) object);
}
if (privkey != null)
{
System.out.println("Algorithm: " + privkey.getAlgorithm()); // ex. RSA
System.out.println("Format: " + privkey.getFormat()); // ex. PKCS#8
}
if (privkey instanceof BCRSAPrivateKey)
{
System.out.println("RSA Key Length: " + ((BCRSAPrivateKey)privkey).getModulus().bitLength()); // ex. 2048
}
if (privkey instanceof BCDSAPrivateKey)
{
System.out.println("DSA Key Length: " + ((BCDSAPrivateKey)privkey).getParams().getP().bitLength()); // ex. 2048
}
if (privkey instanceof BCECPrivateKey)
{
System.out.println("EC Key Length: " + ((BCECPrivateKey)privkey).getParams().getOrder().bitLength()); // ex. 256
}
}
}
Update: I've edited the code above to give key lengths for RSA, DSA, and EC keys.