security
Get DSA parameters of a key pair example
This is an example of how to get DSA parameters of a key pair. In short, to get the DSA parameters of a key pair you should:
- Generate a 1024-bit Digital Signature Algorithm (DSA) key pair. Create a KeyPairGenerator for the DSA algorithm and initialize it with 1024-bit key size.
- Generate the KeyPair.
- Get the private and public key from the key pair and cast them to
sun.security.provider.DSAPrivateKey
andsun.security.provider.DSAPublicKey
correspondingly. - Get the DSAParams of the private key. THe DSAParams consist of three BigInteger parameters, the prime, the subPrime and the base. Retrieve them all with the API methods provided by the DSAParams Class.
- Get the raw private and the raw public key.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.math.BigInteger; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.interfaces.DSAParams; import sun.security.provider.DSAPrivateKey; import sun.security.provider.DSAPublicKey; public class DSAParamsOfKeyPair { public static void main(String[] args) { try { // Generate a 1024-bit Digital Signature Algorithm (DSA) key pair KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA"); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.genKeyPair(); DSAPrivateKey privateKey = (DSAPrivateKey) keyPair.getPrivate(); DSAPublicKey publicKey = (DSAPublicKey) keyPair.getPublic(); /* * DSA requires three parameters to create a key pair * prime (P) * subprime (Q) * base (G) * These three values are used to create a private key (X) * and a public key (Y) */ DSAParams dsaParams = privateKey.getParams(); BigInteger prime = dsaParams.getP(); BigInteger subPrime = dsaParams.getQ(); BigInteger base = dsaParams.getG(); BigInteger x = privateKey.getX(); BigInteger y = publicKey.getY(); } catch (NoSuchAlgorithmException e) { } } }
This was an example of how to get the DSA parameters of a key pair in Java.