Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Byte array to PrivateKey or PublicKey type?

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?

like image 987
sufala Avatar asked Oct 14 '13 04:10

sufala


1 Answers

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)); 
like image 172
nsayer Avatar answered Oct 07 '22 17:10

nsayer