Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Cryptographic Interoperability: Keys

, 5 Jun 2008
Import and export Cryptographic Keys in PKCS#8 and X.509 formats, using Crypto++, C#, and Java.
cryptoppinteropkeys.zip
CryptoPPInteropKeys
CryptoPPInteropKeys
csinteropkeys.zip
CSInteropKeys
CSInteropKeys
Properties
javainteropkeys.zip
JavaInteropKeys
manifest.mf
nbproject
genfiles.properties
private
private.properties
project.properties
src
JavaInteropKeys
test
package JavaInteropKeys;
      
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyFactory;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
 
/**
 * @author jeffrey walton
 **/
public class Main
{
    public static void main(String[] args) throws Exception
    {
        final String PRIVATE_KEY_FILE = "private.rsa.java.key";
        final String PUBLIC_KEY_FILE = "public.rsa.java.key";
 
        // http://java.sun.com/j2se/1.4.2/docs/guide/security/CryptoSpec.html
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
 
        // Initialize
        kpg.initialize(1024, new SecureRandom());
        KeyPair keys = kpg.generateKeyPair();
 
        RSAPrivateKey privateKey = (RSAPrivateKey) keys.getPrivate();
        RSAPublicKey publicKey = (RSAPublicKey) keys.getPublic();
 
        // Print Parameters
        PrintPrivateKey(privateKey);
        PrintPublicKey(publicKey);
 
        // Serialize Keys
        SaveKey(PRIVATE_KEY_FILE, privateKey);
        SaveKey(PUBLIC_KEY_FILE, publicKey);
 
        // PrivateKey privateKey = LoadPrivateKey("private.java.key");
        privateKey = LoadPrivateKey(PRIVATE_KEY_FILE);
        PrintPrivateKey(privateKey);
 
        // PublicKey publicKey = LoadPublicKey("public.java.key");
        publicKey = LoadPublicKey(PUBLIC_KEY_FILE);
        PrintPublicKey(publicKey);
    }
 
    static void SaveKey(String filename, Key key) throws IOException
    {
        if (null == key)
        {
            throw new IllegalArgumentException("key is null.");
        }
 
        DataOutputStream dos =
              new DataOutputStream(new FileOutputStream(filename));
 
        // PKCS #8 for Private, X.509 for Public
        // File will contain OID 1.2.840.11359.1.1.1 (RSA)
        // http://java.sun.com/j2se/1.4.2/docs/api/java/security/Key.html
        dos.write(key.getEncoded());
 
        dos.close();
    }
 
    static RSAPrivateKey LoadPrivateKey(String filename) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException
    {
        File file = new File(filename);
        byte[] b = fullyReadFile(file);
 
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(b);
 
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return (RSAPrivateKey) factory.generatePrivate(spec);
    }
 
    static RSAPublicKey LoadPublicKey(String filename) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException
    {
        File file = new File(filename);
        byte[] b = fullyReadFile(file);
 
        X509EncodedKeySpec spec = new X509EncodedKeySpec(b);
 
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return (RSAPublicKey) factory.generatePublic(spec);
    }
 
    private static byte[] fullyReadFile(File file) throws IOException
    {
        DataInputStream dis = new DataInputStream(new FileInputStream(file));
        byte[] bytesOfFile = new byte[(int) file.length()];
        dis.readFully(bytesOfFile);
        dis.close();
        return bytesOfFile;
    }
 
    static void PrintPrivateKey(RSAPrivateKey key)
    {
        if (null == key)
        {
            throw new IllegalArgumentException("key is null.");
        }
 
        System.out.print("Private Key ");
        System.out.println("(" + key.getFormat() + ")");
        System.out.println(" d: " + key.getPrivateExponent());
        System.out.println(" n: " + key.getModulus());
 
        System.out.println();
    }
 
    static void PrintPublicKey(RSAPublicKey key)
    {
        if (null == key)
        {
            throw new IllegalArgumentException("key is null.");
        }
 
        System.out.print("Public Key ");
        System.out.println("(" + key.getFormat() + ")");
        System.out.println(" e: " + key.getPublicExponent());
        System.out.println(" n: " + key.getModulus());
 
        System.out.println();
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Jeffrey Walton
Systems / Hardware Administrator
United States United States
No Biography provided

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 5 Jun 2008
Article Copyright 2008 by Jeffrey Walton
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid