How to generate key in java

Generate RSA keys and write to a PEM file in Java

In this tutorial we will learn how to generate RSA keys in Java and write them to PEM files. BouncyCastle will be used to do this task. BouncyCastle is a library that consist, among others, of a JCE/JCA provider (Java Cryptography Extension/Java Cryptography Architecture) and a set of classes to handle PEM files.

To deal with this tutorial it is required:

Table of Contents

1. Create a Maven project

Having Maven installed and its environment variables properly configured, execute the following command in a shell:

mvn archetype:generate -DgroupId=com.txedo.security -DartifactId=bouncycastle-pem-write -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false 

As result, a Maven project will be created in your current working directory. Finally, import the project in your IDE.

Project structure: Generate RSA keys and write to a PEM file in Java

2. Configure the POM file

Add the BouncyCastle library to the Maven dependencies. In the snippet below, we also added the log4j dependency to print some debug traces in our program.

 xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.txedo.security bouncycastle-pem-write 0.0.1-SNAPSHOT   org.bouncycastle bcprov-jdk15on 1.51   log4j log4j 1.2.17    

3. Create a class to encapsulate I/O operations and PEM file handling logic

We have created the class PemFile that encapsulates the creation of a PemObject , included in the BouncyCastle library, and the file write operation.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.security.Key; import org.bouncycastle.util.io.pem.PemObject; import org.bouncycastle.util.io.pem.PemReader; import org.bouncycastle.util.io.pem.PemWriter; public class PemFile  private PemObject pemObject; public PemFile (Key key, String description)  this.pemObject = new PemObject(description, key.getEncoded()); > public void write(String filename) throws FileNotFoundException, IOException  PemWriter pemWriter = new PemWriter(new OutputStreamWriter(new FileOutputStream(filename))); try  pemWriter.writeObject(this.pemObject); > finally  pemWriter.close(); > > > 

4. Create the main program class

The main program class responsibility is to create the RSA keys and to orchestrate everything. Optionally, we added the BouncyCastle provider (line 21). The BouncyCastle is used later to get the KeyPairGenerator singleton instance (line 34). Once the keys are created (lines 25-26), the private key and public key are written to the id_rsa and id_rsa.pub files, respectively.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
import java.io.FileNotFoundException; import java.io.IOException; import java.security.Key; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Security; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import org.apache.log4j.Logger; import org.bouncycastle.jce.provider.BouncyCastleProvider; public class Main  protected final static Logger LOGGER = Logger.getLogger(Main.class); public static final int KEY_SIZE = 1024; public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchAlgorithmException, NoSuchProviderException  Security.addProvider(new BouncyCastleProvider()); LOGGER.info("BouncyCastle provider added."); KeyPair keyPair = generateRSAKeyPair(); RSAPrivateKey priv = (RSAPrivateKey) keyPair.getPrivate(); RSAPublicKey pub = (RSAPublicKey) keyPair.getPublic(); writePemFile(priv, "RSA PRIVATE KEY", "id_rsa"); writePemFile(pub, "RSA PUBLIC KEY", "id_rsa.pub"); > private static KeyPair generateRSAKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException  KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC"); generator.initialize(KEY_SIZE); KeyPair keyPair = generator.generateKeyPair(); LOGGER.info("RSA key pair generated."); return keyPair; > private static void writePemFile(Key key, String description, String filename) throws FileNotFoundException, IOException  PemFile pemFile = new PemFile(key, description); pemFile.write(filename); LOGGER.info(String.format("%s successfully writen in file %s.", description, filename)); > > 

5. Execute the program

Once the program is executed, we get a console output like this:

Main:26 - BouncyCastle provider added. Main:42 - RSA key pair generated. Main:51 - RSA PRIVATE KEY successfully writen in file id_rsa. Main:51 - RSA PUBLIC KEY successfully writen in file id_rsa.pub. 

And two files named id_rsa and id_rsa.pub containing the private key and the public key:

-----BEGIN RSA PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJLORhDfV6VwpZCF 0ZgCKc7cP3Sy5EFkkHY1LKDNqhYmU+ey7GzNjJbm/JIZQwtufcpP8K14kEq2rHo/ F2hN5DQ0hRpSAXljxuz0Y0l5DeELQYrYjcjFMOU5071ebBNuCxm7x3hqSXt/LlmW GBo73rf3cksI5sxlKEvr69fl4vUJAgMBAAECgYBViTxHzmn56hV9jIrff7suXSPX 8feOpnKJfVgAZXSJrVFL+fNJPcaBkhptYayvt3QxcbxwxoOEFMWQALy5uFCSuWk8 WOiUVlVoCZUjW1fn6z3N0WiuW0yJH315yYjHunFI9THaToIT8XXANZPMS6Jw84Qy EmNKF6DgirYKvmEyAQJBAORadaff+2yh9r8r25SIIujQpogYMB+JbyAtfSwHMPIC ZWC137ah1hYj82KutL0yQ9r/6iM+/lY9a5W6SvpWpkECQQCklFfjFxlQ13VrkrGp h8duqbWm0BdX32lqaTNPscDaz60GWw7LPNhb0LY2mlTP1iSgWdt3VCWKvowHA1Qh 92zJAkANxEJZl5BB0VXd2pgHUVnBbWrMw6CLFi8D4posQFa8EFbqSKyvBvywIwS2 S1AMI+6hUlJcQ5zzuAo3YZ7JjtXBAkARrd3DBzgw9vQmGhv7mhpSSOi6gp//UICC bcqVRQLyflyX0jBEpMSZGFJ6ixmROe+1SfHJX8Cops9j8XeYLnwBAkEAqxZUZ4NB kfTwjtxIsZhwaBHKPduFPg+kSKCvTwqpn87D2E0jk/dL4oFk3/otj4L1j1aelFb8 hmciN50QAVL2Bg== -----END RSA PRIVATE KEY----- 
-----BEGIN RSA PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCSzkYQ31elcKWQhdGYAinO3D90 suRBZJB2NSygzaoWJlPnsuxszYyW5vySGUMLbn3KT/CteJBKtqx6PxdoTeQ0NIUa UgF5Y8bs9GNJeQ3hC0GK2I3IxTDlOdO9XmwTbgsZu8d4akl7fy5ZlhgaO96393JL CObMZShL6+vX5eL1CQIDAQAB -----END RSA PUBLIC KEY----- 

Download the code

The code used in this article to generate RSA keys and write them to a PEM file can be found in GitHub:

References

Software Development Engineer with extensive experience in information systems and microservices deployed in the cloud.

Expert in Java and Spring ecosystem. Read more about me.

txedo.com

This blog is built using Jekyll and proudly hosted by DigitalOcean® App Platform.

Contents of this website are © 2020 under the terms of the MIT License.

Source code related to the contents of this blog is open source and can be downloaded from GitHub.

Источник

Generate Keys

If a code signer does not yet have a suitable private key for signing the code, the key must first be generated, along with a corresponding public key that can be used by the code receiver's runtime system to verify the signature.

Since this lesson assumes that you don't yet have such keys, you are going to create a keystore named examplestore and create an entry with a newly generated public/private key pair (with the public key in a certificate).

Type the following command in your command window to create a keystore named examplestore and to generate keys:

keytool -genkey -alias signFiles -keystore examplestore 

You will be prompted to enter passwords for the key and keystore.

Subparts of the keytool Command

Let's look at what each of the keytool subparts mean.

  • The command for generating keys is -genkey.
  • The -alias signFiles subpart indicates the alias to be used in the future to refer to the keystore entry containing the keys that will be generated.
  • The -keystore examplestore subpart indicates the name (and optionally path) of the keystore you are creating or already using.
  • The storepass value that you are promted for specifies the keystore password.
  • The keypass value that you are prompted for specifies a password for the private key about to be generated. You will always need this password in order to access the keystore entry containing that key. The entry doesn't have to have its own password. When you are prompted for the key password, you are given the option of letting it be the same as the keystore password.

Note: For security reasons you should not set your key or keystore passwords on the command line, because they can be intercepted more easily that way.

Distinguished-Name Information

If you use the preceding keystore command, you will be prompted for your distinguished-name information. Following are the prompts; the bold indicates what you should type.

What is your first and last name? [Unknown]: Susan Jones What is the name of your organizational unit? [Unknown]: Purchasing What is the name of your organization? [Unknown]: ExampleCompany What is the name of your City or Locality? [Unknown]: Cupertino What is the name of your State or Province? [Unknown]: CA What is the two-letter country code for this unit? [Unknown]: US Is correct? [no]: y 

Command Results

The keytool command creates the keystore named examplestore (if it doesn't already exist) in the same directory in which the command is executed. The command generates a public/private key pair for the entity whose distinguished name has a common name of Susan Jones and the organizational unit of Purchasing.

The command creates a self-signed certificate that includes the public key and the distinguished-name information. (The distinguished name you supply will be used as the "subject" field in the certificate.) This certificate will be valid for 90 days, the default validity period if you don't specify a -validity option. The certificate is associated with the private key in a keystore entry referred to by the alias signFiles .

Self-signed certificates are useful for developing and testing an application. However, users are warned that the application is signed with an untrusted certificate and asked if they want to run the application. To provide users with more confidence to run your application, use a certificate issued by a recognized certificate authority.

Note: The command could be shorter if option defaults are accepted or you wish to be prompted for various values. Whenever you execute a keytool command, defaults are used for unspecified options that have default values, and you are prompted for any required values. For the genkey command, options with default values include alias (whose default is mykey ), validity (90 days), and keystore (the file named .keystore in your home directory). Required values include dname, storepass, and keypass.

Источник

Java KeyGenerator

The Java KeyGenerator class ( javax.crypto.KeyGenerator ) is used to generate symmetric encryption keys. A symmetric encryption key is a key that is used for both encryption and decryption of data, by a symmetric encryption algorithm. In this Java KeyGenerator tutorial I will show you how to generate symmetric encryption keys.

Creating a KeyGenerator Instance

Before you can use the Java KeyGenerator class you must create a KeyGenerator instance. You create a KeyGenerator instance by calling the static method getInstance() passing as parameter the name of the encryption algorithm to create a key for. Here is an example of creating a Java KeyGenerator instance:

KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

This example creates a KeyGenerator instance which can generate keys for the AES encryption algorithm.

Initializing the KeyGenerator

After creating the KeyGenerator instance you must initialize it. Initializing a KeyGenerator instance is done by calling its init() method. Here is an example of initializing a KeyGenerator instance:

SecureRandom secureRandom = new SecureRandom(); int keyBitSize = 256; keyGenerator.init(keyBitSize, secureRandom);

The KeyGenerator init() method takes two parameters: The bit size of the keys to generate, and a SecureRandom that is used during key generation.

Generating a Key

Once the Java KeyGenerator instance is initialized you can use it to generate keys. Generating a key is done by calling the KeyGenerator generateKey() method. Here is an example of generating a symmetric key:

SecretKey secretKey = keyGenerator.generateKey();

Источник

Читайте также:  Метод poll queue java
Оцените статью