Transform a BigInteger RSA private key into a RSAPrivateKey object - Java Security

Java examples for Security:DSA

Description

Transform a BigInteger RSA private key into a RSAPrivateKey object

Demo Code

/*/*from   w w  w  . ja v  a2  s . com*/
 * Copyright (c) 2014 Berner Fachhochschule, Switzerland.
 * Bern University of Applied Sciences, Engineering and Information Technology,
 * Research Institute for Security in the Information Society, E-Voting Group,
 * Biel, Switzerland.
 *
 * Project UniBoard.
 *
 * Distributable under GPL license.
 * See terms of license at gnu.org.
 */
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.DSAPrivateKeySpec;
import java.security.spec.DSAPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main{
    private static final Logger logger = Logger.getLogger(PostHelper.class
            .getName());
    /**
     * Transform a BigInteger RSA private key into a RSAPrivateKey object
     *
     * @param modulus value of RSA modulus
     * @param d value of private key
     * @return the corresponding RSAPrivateKey object, null if an error occured
     * @throws InvalidKeySpecException if values do not represent a valid private key
     */
    public static RSAPrivateKey createRSAPrivateKey(BigInteger modulus,
            BigInteger d) throws InvalidKeySpecException {

        RSAPrivateKeySpec spec = new RSAPrivateKeySpec(modulus, d);
        KeyFactory keyFactory;
        try {
            keyFactory = KeyFactory.getInstance("RSA");
        } catch (NoSuchAlgorithmException ex) {
            logger.log(Level.SEVERE, "Invalid key algorithm given.", ex);
            return null;
        }
        return (RSAPrivateKey) keyFactory.generatePrivate(spec);
    }
}

Related Tutorials