Transform a BigInteger DSA public key into a DSAPublicKey object - Java Security

Java examples for Security:DSA

Description

Transform a BigInteger DSA public key into a DSAPublicKey object

Demo Code

/*/*from  ww  w.ja v a2 s  . c om*/
 * 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 DSA public key into a DSAPublicKey object
     *
     * @param p value of prime p
     * @param q value of prime q
     * @param g value of generator g
     * @param y value of public key y
     * @return the corresponding DSAPublicKey object, null if an error occured
     * @throws InvalidKeySpecException if values do not represent a valid public key
     */
    public static DSAPublicKey createDSAPublicKey(BigInteger p,
            BigInteger q, BigInteger g, BigInteger y)
            throws InvalidKeySpecException {

        DSAPublicKeySpec keySpec = new DSAPublicKeySpec(y, p, q, g);
        KeyFactory keyFactory;
        try {
            keyFactory = KeyFactory.getInstance("DSA");
        } catch (NoSuchAlgorithmException ex) {
            logger.log(Level.SEVERE, "Invalid key algorithm given.", ex);
            return null;
        }
        return (DSAPublicKey) keyFactory.generatePublic(keySpec);
    }
}

Related Tutorials