How to use RSAPublicKey and RSAPrivateKey classes in Java? - java

I am trying to use [Java JWT] library(https://github.com/auth0/java-jwt) to generate JWT and I require to make instances of private key and public key i.e. RSAPrivateKey and RSAPublicKey.
//RSA
RSAPublicKey publicKey = //Get the key instance
RSAPrivateKey privateKey = //Get the key instance
Algorithm algorithmRS = Algorithm.RSA256(publicKey, privateKey);
How do I create the instances of RSAPrivateKey and RSAPublicKey?
I have created .pem files using OpenSSL (if that helps) but I am not able to use that too.

First create the KeyPairGenerator to create the KeyPairs.
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
This will give you a KeyPairGenerator using RSA. Next you initialize the generator with the amount of bytes you want it to use and then create the KeyPair.
kpg.initialize(1024);
KeyPair kp = kpg.generateKeyPair();
Get the PublicKey and PrivateKey from the KeyPair kp using their Getters and than because RsaPublicKey is just a a SubClass of Key and we made these keys with RSA we can safely cast the PublicKey and PrivateKey classes to RSAPublicKey and RSAPrivateKey
RSAPublicKey rPubKey = (RSAPublicKey) kp.getPublic();
RSAPrivateKey rPriKey = (RSAPrivateKey) kp.getPrivate();

Related

How can I generate an EC KeyPair from a PrivateKey string?

I generated a KeyPair like this:
ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256k1");
KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
generator.initialize(ecSpec, new SecureRandom());
KeyPair kp = generator.generateKeyPair();
Then I generate Strings from the KeyPair:
String privateKeyString = Base64.getEncoder().encodeToString(kp.getPrivate().getEncoded();
So my first Question is how can I generate a PrivateKey object from privateKeyString and my second question is how can I generate a PublicKey / KeyPair from the PrivateKey object?

Reconstructing private and public keys with Bouncy Castle?

If I get the actual key with getEncoded from a public or a private key in Bouncy Castle in Java (actual class seems to be BCECPublicKey and BCECPrivateKey). Is it possible to reconstruct the key objects to use them in code?
I found out here in Stack Overflow how to serialize the whole object to binary (and then to disk) and then back to binary and to an object of the appropriate class, but I believe that serialization contains implementation details and if I try to use those keys with anything else than Bouncy Castle, it'll fail. I'm not trying to do that now, but I want to future-proof my program.
This is how I'm creating the keys:
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");
keyPairGenerator.initialize(new ECGenParameterSpec("secp521r1"), new SecureRandom());
java.security.KeyPair keyPair = keyPairGenerator.generateKeyPair();
privateKey = keyPair.getPrivate();
publicKey = keyPair.getPublic();
The KeyFactory is used to convert between encoded keys and the Java classes that represent them. However, the KeyFactory instance doesn't convert directly between a byte array and a Key class. Instead, you must already know what format the encoding uses, and then create a KeySpec object using the byte array in the constructor. The format can be determined by called the getFormat() method on the key. Here is an example illustrating some of these points.
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class Main {
public static void main(String[] args) throws Exception{
Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");
keyPairGenerator.initialize(new ECGenParameterSpec("secp521r1"), new SecureRandom());
java.security.KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
System.out.println(privateKey.getFormat());
PublicKey publicKey = keyPair.getPublic();
System.out.println(publicKey.getFormat());
// A KeyFactory is used to convert encoded keys to their actual Java classes
KeyFactory ecKeyFac = KeyFactory.getInstance("EC", "BC");
// Now do a round-trip for a private key,
byte [] encodedPriv = privateKey.getEncoded();
// now take the encoded value and recreate the private key
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(encodedPriv);
PrivateKey privateKey2 = ecKeyFac.generatePrivate(pkcs8EncodedKeySpec);
// And a round trip for the public key as well.
byte [] encodedPub = publicKey.getEncoded();
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(encodedPub);
PublicKey publicKey2 = ecKeyFac.generatePublic(x509EncodedKeySpec);
System.out.println(publicKey2);
}
}

Getting modulus and publicExponent from java PublicKey

Hi all I get the public key as follows
OpenSSLRSAPublicKey{modulus=e6f4b594e1757261a98abe478f47b941cf8339933accc57d73d18bb8da906cf628da1949fb71c51f1635d93067ca2993599965f42d26237f63c1bc333de779051c36805f00ab5698a78e5616a7a7b0df487ba0fb3a89592780984562b96387443774331358a5920815bba2e24ad6c6c4ba6c7f52384847b4feea20190acdef000f6ee078352c0e0764e51dab25037d3d9c819a9be9ea240260ca2217ea4b446caf05d14318941a844ee82f567382c9fad8b959481c27785cdf6cb22ecf80f51bddc9f1c918d56b9bdd80ba4e766209069d0cf2012c0f15dbe4a8b5c2588a0ce295c2e90d44a52190289ab2fdceb22feffdadf623cab33e6a2e98be662cd5fecb,publicExponent=10001}
by using the bellow code
KeyPairGenerator kpg;
KeyPair kp;
PublicKey publicKey;
kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
kp = kpg.genKeyPair();
publicKey = kp.getPublic();
now i want to get the modulus and publicExponent from this.
Can any one suggest please...?
You have to cast the PublicKey to an RSAPublicKey, e.g.
RSAPublicKey rsaPub = (RSAPublicKey)(kp.getPublic());
BigInteger modulus = rsaPub.getModulus();
BigInteger publicExponent = rsaPub getPublicExponent()

Write public key on a file and read with objectInputStream

I need to save a public key in a file and then read.
So, i do this mainly steps:
KeyPair keyPair = kpg.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
Then i save with objectOutputStream
Now i creae an objetInputStream with the file that contains that key.
Now im doing:
PublicKey pub = (PublicKey)pReader.readObject();
And i get the exception:
java.lang.ClassCastException: sun.security.rsa.RSAPrivateCrtKeyImpl cannot be cast to java.security.PublicKey.
Thanks
Obviously you must be saving the private key, not the public key.

Asymmertic key encryption not working

Below mentioned is a code which is showing exception while running. Wanted to understand the public key / private key working.
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = generator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
aes.init(Cipher.ENCRYPT_MODE,publicKey);
byte[] cipherText = aes.doFinal("my password".getBytes());
System.out.println(new String(cipherText));
Below mentioned is exception.
Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters

Categories