KeyFactory generatePrivate() method in Java with Examples
Last Updated :
06 Nov, 2019
The generatePrivate() method of java.security.KeyPairGenerator class is used to generates a private key object from the provided key specification (key material).
Syntax:
public final PrivateKey generatePrivate(KeySpec keySpec)
throws InvalidKeySpecException
Parameters: This method takes keySpec(the specification (key material) of the private key) as a parameter.
Return Value: This method returns the private key.
Exception: This method throws InvalidKeySpecException if the given key specification is inappropriate for this key factory to produce a private key.
Below are the examples to illustrate the generatePrivate() method
Note: The following program will not run on online IDE
Example 1:
import java.security.*;
import java.util.*;
import java.security.spec.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
KeyPairGenerator kpg = KeyPairGenerator
.getInstance( "DSA" );
kpg.initialize( 1024 );
KeyPair kp = kpg.genKeyPair();
PrivateKey prv = kp.getPrivate();
byte [] private KeyBytes = prv.getEncoded();
EncodedKeySpec
private KeySpec
= new PKCS8EncodedKeySpec( private KeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance( "DSA" );
PrivateKey private Key = keyFactory
.generatePrivate( private KeySpec);
System.out.println( "PrivateKey : " + private Key);
}
catch (NoSuchAlgorithmException e) {
System.out.println( "Exception thrown : " + e);
}
catch (ProviderException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
PrivateKey : sun.security.provider.DSAPrivateKey@fff96ed9
Example 2: For InvalidKeySpecException
import java.security.*;
import java.util.*;
import java.security.spec.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
KeyPairGenerator kpg = KeyPairGenerator
.getInstance( "DSA" );
kpg.initialize( 1024 );
KeyPair kp = kpg.genKeyPair();
PrivateKey prv = kp.getPrivate();
byte [] private KeyBytes = prv.getEncoded();
EncodedKeySpec
private KeySpec
= new X509EncodedKeySpec( private KeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance( "DSA" );
PrivateKey private Key = keyFactory
.generatePrivate( private KeySpec);
System.out.println( "Private Key : " + private Key);
}
catch (NoSuchAlgorithmException e) {
System.out.println( "Exception thrown : " + e);
}
catch (ProviderException e) {
System.out.println( "Exception thrown : " + e);
}
catch (InvalidKeySpecException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Exception thrown : java.security.spec.InvalidKeySpecException:
Inappropriate key specification
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...