takes bytes of PrivateKey saved in database and converts back to PrivateKey. - Java Security

Java examples for Security:Key

Description

takes bytes of PrivateKey saved in database and converts back to PrivateKey.

Demo Code


//package com.java2s;

import java.security.KeyFactory;

import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;

import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

public class Main {
    /**//from ww w . ja v a  2 s . c  o m
     * takes bytes of PrivateKey saved in database and converts back to PrivateKey.
     *
     * @param  savedKey
     *
     * @return
     *
     * @throws  NoSuchAlgorithmException
     * @throws  InvalidKeySpecException
     */
    public static PrivateKey getPrivateKeyByBytes(byte[] savedKey)
            throws NoSuchAlgorithmException, InvalidKeySpecException {

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(savedKey);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        PrivateKey privKey = keyFactory.generatePrivate(keySpec);

        return privKey;
    }
}

Related Tutorials