Generate RSA key which contains a pair of private and public key using 1024 bytes. - Android java.security

Android examples for java.security:RSA

Description

Generate RSA key which contains a pair of private and public key using 1024 bytes.

Demo Code


//package com.java2s;

import java.io.File;

import java.io.FileOutputStream;

import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;

public class Main {
    /**/* ww  w . j a va2 s  .co  m*/
     * String to hold name of the encryption algorithm.
     */
    public static final String ALGORITHM = "RSA";
    /**
     * String to hold the name of the private key file.
     */
    public static final String PRIVATE_KEY_FILE = "/Users/thijs/private.key";
    /**
     * String to hold name of the enc key file.
     */
    public static final String PUBLIC_KEY_FILE = "res/key/enc.key";

    /**
     * Generate key which contains a pair of private and public key using 1024
     * bytes. Store the set of keys in Private.key and Public.key files.
     *
     * @throws NoSuchAlgorithmException
     * @throws IOException
     * @throws FileNotFoundException
     */
    public static void generateKey() {
        try {

            // set algorithm to be used for key
            final KeyPairGenerator keyGen = KeyPairGenerator
                    .getInstance(ALGORITHM);
            // set encryption strength
            keyGen.initialize(1024);
            // generate keypair
            final KeyPair key = keyGen.generateKeyPair();

            File privateKeyFile = new File(PRIVATE_KEY_FILE);
            File publicKeyFile = new File(PUBLIC_KEY_FILE);

            // Create files to store enc and private key
            if (privateKeyFile.getParentFile() != null) {
                privateKeyFile.getParentFile().mkdirs();
            }
            privateKeyFile.createNewFile();

            if (publicKeyFile.getParentFile() != null) {
                publicKeyFile.getParentFile().mkdirs();
            }
            publicKeyFile.createNewFile();

            // save the Public key to a file
            ObjectOutputStream publicKeyOS = new ObjectOutputStream(
                    new FileOutputStream(publicKeyFile));
            publicKeyOS.writeObject(key.getPublic());
            publicKeyOS.close();

            // save the Private key to a file
            ObjectOutputStream privateKeyOS = new ObjectOutputStream(
                    new FileOutputStream(privateKeyFile));
            privateKeyOS.writeObject(key.getPrivate());
            privateKeyOS.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Related Tutorials