How do I generate public and private keys?

The code snippet below show you how to use the JDK Security API to generate public and private keys. A private key can be use to sign a document and the public key is use to verify that the signature of the document is valid.

The API we use to generate the key pairs is in the package. That’s mean we have to import this package into our code. The class for generating the key pairs is KeyPairGenerator. To get an instance of this class we have to call the getInstance() methods by providing two parameters. The first parameter is algorithm and the second parameter is the provider.

After obtaining an instance of the key generator we have to initialize it. The initialize() method takes two parameters, the key size and a source of randomness. We set the key size to 1024 and pass and instance of SecureRandom.

Finally to generate the key pairs we call the generateKeyPair() method of the KeyPairGenerator class. This will return a KeyPair object from where we can get the PrivateKey and PublicKey by calling the getPrivate() and getPublic() method.

Let’s see the code snippet below:


import java.util.Base64;

public class GenerateKeyPairDemo {
    public static void main(String[] args) {
        try {
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");

            // Initialize KeyPairGenerator.
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
            keyGen.initialize(1024, random);

            // Generate Key Pairs, a private key and a public key.
            KeyPair keyPair = keyGen.generateKeyPair();
            PrivateKey privateKey = keyPair.getPrivate();
            PublicKey publicKey = keyPair.getPublic();

            Base64.Encoder encoder = Base64.getEncoder();
            System.out.println("privateKey: " + encoder.encodeToString(privateKey.getEncoded()));
            System.out.println("publicKey: " + encoder.encodeToString(publicKey.getEncoded()));
        } catch (NoSuchAlgorithmException e) {
        } catch (NoSuchProviderException e) {

How do I get cryptographic security providers?


import java.util.Set;
import java.util.HashSet;

public class SecurityProvider {
    public static void main(String[] args) {
        // Create a set so that we can have a unique result.
        Set result = new HashSet();

        // Returns an array containing all the installed providers.
        Provider[] providers = Security.getProviders();

        for (Provider provider : providers) {

            // Get provider's property keys
            Set keys = provider.keySet();
            for (Object key : keys) {
                String data = (String) key;
                data = data.split(" ")[0];

                // Service type started by the "Alg.Alias" string
                if (data.startsWith("Alg.Alias")) {
                    data = data.substring(10);

                data = data.substring(0, data.indexOf('.'));

        for (Object o : result) {
            System.out.println("Service Type = " + o);

The example result of our code:

Service Type = KeyFactory
Service Type = TransformService
Service Type = CertPathBuilder
Service Type = Cipher
Service Type = SecureRandom
Service Type = Signature
Service Type = AlgorithmParameterGenerator
Service Type = KeyPairGenerator
Service Type = XMLSignatureFactory
Service Type = CertificateFactory
Service Type = MessageDigest
Service Type = KeyInfoFactory
Service Type = KeyAgreement
Service Type = CertStore
Service Type = Configuration
Service Type = SSLContext
Service Type = SaslServerFactory
Service Type = AlgorithmParameters
Service Type = TrustManagerFactory
Service Type = GssApiMechanism
Service Type = TerminalFactory
Service Type = Mac
Service Type = KeyGenerator
Service Type = Policy
Service Type = CertPathValidator
Service Type = SaslClientFactory
Service Type = SecretKeyFactory
Service Type = KeyManagerFactory
Service Type = KeyStore
Service Type = Provider

How do I create an encrypted string for password?

You are creating a user management system that will keep user profile and their credential or password. For security reason you’ll need to protect the password, to do this you can use the MessageDigest provided by Java API to encrypt the password. The code example below show you an example how to use it.



public class EncryptExample {
    public static void main(String[] args) {
        String password = "secret";
        String algorithm = "SHA";

        byte[] plainText = password.getBytes();

        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);

            byte[] encodedPassword = md.digest();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < encodedPassword.length; i++) {
                if ((encodedPassword[i] & 0xff) < 0x10) {

                sb.append(Long.toString(encodedPassword[i] & 0xff, 16));

            System.out.println("Plain    : " + password);
            System.out.println("Encrypted: " + sb.toString());
        } catch (Exception e) {

Here is the example of our encrypted password:

Plain    : secret
Encrypted: e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4