How to convert Byte array to PrivateKey or PublicKey type?

42,377

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));
Share:
42,377
sufala
Author by

sufala

Updated on July 08, 2020

Comments

  • sufala
    sufala almost 4 years

    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?

  • Dean Blakely
    Dean Blakely over 8 years
    I've searched for 2 days to find how to convert RSA keys to strings and back and this is the ONLY post that has a working solution. Thanks nsayer!
  • alper
    alper almost 8 years
    well you cannot give object name as "public" or "private".
  • Wheezil
    Wheezil about 5 years
    Note that getEncoded() on a key doesn't tell you what is the encoding. The Key interface has getFormat(), which returns a string indicating the format, but then you have to know what class goes with each format. Seems like a standard ServiceLoader could help this?