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.
Related
I had generate public key using Java Spring Security, but I can not use that public key to encrypt the data using Nodejs crypto library. I think it is because of its format(X509).
My Nodejs code
module.exports.encryptRsa = (toEncrypt, pemPath) => {
let absolutePath = path.resolve(pemPath);
let publicKey = fs.readFileSync(absolutePath, "utf8");
let buffer = Buffer.from(toEncrypt);
let encrypted = crypto.publicEncrypt(publicKey, buffer);
return encrypted.toString("base64");
};
My Java code
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyAlgorithm);
keyGen.initialize(2048);
KeyPair keyPair = keyGen.genKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
byte[] privateKeyBytes = privateKey.getEncoded();
byte[] publicKeyBytes = publicKey.getEncoded();
String formatPrivate = privateKey.getFormat(); // PKCS#8
String formatPublic = publicKey.getFormat(); // X.509
FileWriter fos = new FileWriter("publicKey.pem");
fos.write("-----BEGIN RSA PUBLIC KEY-----\n");
fos.write(enc.encodeToString(publicKeyBytes));
fos.write("\n-----END RSA PUBLIC KEY-----\n");
fos.close();
Java's getEncoded() method returns the public key in format called 'spki' by Node crypto. Java's name for that format is "X.509", an unfortunate choice because it causes confusion with certificates of that name.
The proper PEM header for spki keys is simply -----BEGIN PUBLIC KEY-----. Just get rid of RSA in the header and footer.
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
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();
I have to use DSA (Digital Signature Algorithm) in my project, implementing using Java.I have a problem that I can't store the public and private key of DSA (of type PublicKey & PrivateKey). When I stored it as a blob, can't retrieve to its form (ie., PublicKey). Can anyone help me?
KeyPairGenerator pairgen = KeyPairGenerator.getInstance("DSA");
SecureRandom random = new SecureRandom();
pairgen.initialize(KEYSIZE, random);
KeyPair keyPair = pairgen.generateKeyPair();
PublicKey pu=keyPair.getPublic();
I have to store this up and have to retrieve
Store it as byte[] using pu.getEncoded().
To restore into PublicKey object you load the byte array and make the following call
KeyFactory kf = KeyFactory.getInstance("DSA");
PublicKey pu = kf.generatePublic(new X509EncodedKeySpec(keyBytes));
Optionally you can also encode it with base64.
I am using RSA algorithm to generate public and private key
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
final KeyPair key = keyGen.generateKeyPair();
final PrivateKey privateKey=key.getPrivate();
final PublicKey publickey=key.getPublic();
after that these keys are encoded using Base64 encoder and save it into database.
How to convert this encoded String to Private and Public Key Type in java is to decrypt file.
when decoding this String using Base64Decoder will get a byte array. how to convert this Byte array to public or private key type?
If you have a byte[] representing the output of getEncoded() on a key, you can use KeyFactory to turn that back into a PublicKey object or a PrivateKey object.
byte[] privateKeyBytes;
byte[] publicKeyBytes;
KeyFactory kf = KeyFactory.getInstance("RSA"); // or "EC" or whatever
PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
PublicKey publicKey = kf.generatePublic(new X509EncodedKeySpec(publicKeyBytes));