Asymmertic key encryption not working - java

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

Related

Java: Converting between Key type and String

Is it possible to take a public key that I have generated, convert it into a string, reverse the process and use it as a key again?
generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
KeyPair keyPair = generator.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Then convert this to a string:
String public = someMethod(publicKey)
and then Reverse it at a later time:
RSAPublicKey newPublicKey = someMethod(public)
You can convert the Public Key to a String as follows.
String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());
Then that String can be converted back to a public key as follows.
byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyString);
X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey2 = keyFactory.generatePublic(spec);

String to Public key using Base64.getEncoder() [duplicate]

I've used the following code to convert the public and private key to a string
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(2048);
KeyPair keyPair = keyPairGen.genKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
String publicK = Base64.encodeBase64String(publicKey.getEncoded());
String privateK = Base64.encodeBase64String(privateKey.getEncoded());
Now I'm trying to convert it back to public ad private key
PublicKey publicDecoded = Base64.decodeBase64(publicK);
I'm getting error of cannot convert from byte[] to public key. So I tried like this
PublicKey publicDecoded = new SecretKeySpec(Base64.decodeBase64(publicK),"RSA");
This leads to error like below
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: Neither a public nor a private key
Looks like I'm doing wrong key conversion here. Any help would be appreciated.
I don't think you can use the SecretKeySpec with RSA.
This should do:
byte[] publicBytes = Base64.decodeBase64(publicK);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);
And to decode the private use PKCS8EncodedKeySpec

How to use RSAPublicKey and RSAPrivateKey classes in 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();

Encrypting a AES key using RSA Key

I have written a code to encrypt a aes key and decrypt it but it dosent seem to be happening.Why is this so?
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair pair = keyGen.generateKeyPair();
PublicKey pubKey= pair.getPublic();
PrivateKey privateKey = pair.getPrivate();
Cipher c1 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
c1.init(Cipher.ENCRYPT_MODE, pubKey);
KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES");
aesKeyGenerator.init(256);
Key aesKey = rijndaelKeyGenerator.generateKey();
Cipher symmetricCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] encodedKeyBytes = c1.doFinal(aeslKey.getEncoded());
SecretKey aesKey1 = new SecretKeySpec(encodedKeyBytes, "aes1");
Cipher dec = Cipher.getInstance("RSA/ECB/PKCS1Padding");
dec.init(Cipher.DECRYPT_MODE, privateKey);
symmetricCipher.init(Cipher.DECRYPT_MODE, aesKey1, spec);
if(aesKey.getEncoded() == dec.doFinal(c1.doFinal(aesKey.getEncoded())) )
{
// Not reaching here but is supposed to
}
On the line:
SecretKey aesKey1 = new SecretKeySpec(encodedKeyBytes, "aes1");
You are converting the still (RSA) encrypted aesKey to a SecretKey. At that spot you should have decrypted the key first. "aes1" is not any known type of key either.
Please try and separate the various wrapping (key encryption) and encryption statements into methods, and make separate methods for the unwrapping and decryption. Just throwing statements around is not going to get you anywhere. Try to make a methodical attempt to solve the problem at hand.

How to generate a RSA keyPair with a Privatekey encrypted with password?

I want to generate a privatekey PKCS8 format encrypted with password, and I try with this code:
String password = "123456";
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(2048);
KeyPair key = gen.generateKeyPair();
PrivateKey privateKey = key.getPrivate();
PublicKey publicKey = key.getPublic();
FileOutputStream pvt = new FileOutputStream("d:\\pvt123456.der");
try {
pvt.write(privateKey.getEncoded());
pvt.flush();
} finally {
pvt.close();
}
FileOutputStream pub = new FileOutputStream("d:\\pub123456.der");
try {
pub.write(publicKey.getEncoded());
pub.flush();
} finally {
pub.close();
}
But I donĀ“t know how to encrypt a password with 3des to be compatible with openssl format.
I know it's a little bit late but I also have been looking for a way to do this and while i was searching I found your question, now that I have found a way to do this I decided to come back and share this:
// generate key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.genKeyPair();
// extract the encoded private key, this is an unencrypted PKCS#8 private key
byte[] encodedprivkey = keyPair.getPrivate().getEncoded();
// We must use a PasswordBasedEncryption algorithm in order to encrypt the private key, you may use any common algorithm supported by openssl, you can check them in the openssl documentation http://www.openssl.org/docs/apps/pkcs8.html
String MYPBEALG = "PBEWithSHA1AndDESede";
String password = "pleaseChangeit!";
int count = 20;// hash iteration count
SecureRandom random = new SecureRandom();
byte[] salt = new byte[8];
random.nextBytes(salt);
// Create PBE parameter set
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFac = SecretKeyFactory.getInstance(MYPBEALG);
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
Cipher pbeCipher = Cipher.getInstance(MYPBEALG);
// Initialize PBE Cipher with key and parameters
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
// Encrypt the encoded Private Key with the PBE key
byte[] ciphertext = pbeCipher.doFinal(encodedprivkey);
// Now construct PKCS #8 EncryptedPrivateKeyInfo object
AlgorithmParameters algparms = AlgorithmParameters.getInstance(MYPBEALG);
algparms.init(pbeParamSpec);
EncryptedPrivateKeyInfo encinfo = new EncryptedPrivateKeyInfo(algparms, ciphertext);
// and here we have it! a DER encoded PKCS#8 encrypted key!
byte[] encryptedPkcs8 = encinfo.getEncoded();
This example code is based on the folowing code I found: http://www.jensign.com/JavaScience/PEM/EncPrivKeyInfo/EncPrivKeyInfo.java
but the folowing resource also helped me to understand a little bit better: http://java.sun.com/j2se/1.4.2/docs/guide/security/jce/JCERefGuide.html

Categories