Click here to Skip to main content
12,253,371 members (50,873 online)
Click here to Skip to main content

Stats

140K views
9.7K downloads
171 bookmarked
Posted

Cryptographic Interoperability: Digital Signatures

, 20 Oct 2009 CPOL
Sign and verify messages using Crypto++, Java, and C#.
CryptoPPInteropKeys
CryptoPPInteropKeys
CryptoPPInteropSign
CryptoPPInteropSign
CSInteropKeys
CSInteropKeys
Properties
CSInteropSign
CSInteropSign
Properties
JavaInteropKeys
manifest.mf
nbproject
genfiles.properties
private
private.properties
project.properties
src
JavaInteropKeys
test
JavaInteropSign
build
classes
JavaInteropSign
test
classes
results
manifest.mf
nbproject
genfiles.properties
private
private.properties
project.properties
src
JavaInteropSign
test
package JavaInteropKeys;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyFactory;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author jeffrey walton
 **/
public class Main {

  public static void main(String[] args) {
    try {

      // 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
      SaveEncodedKey("private.rsa.java.key", privateKey);
      SaveEncodedKey("public.rsa.java.key", publicKey);

      // PrivateKey privateKey = LoadPrivateKey("private.java.key");
      privateKey = LoadPrivateKey("public.rsa.cpp.key");
      PrintPrivateKey(privateKey);

      // PublicKey publicKey = LoadPublicKey("public.java.key");
      publicKey = LoadPublicKey("public.rsa.cpp.key");
      PrintPublicKey(publicKey);

    } catch (Exception e) {
      System.err.println("Main: " + e.toString());
    }
  }

  static void SaveEncodedKey(String filename, Key key) {
    try {

      if (null == key) {
        throw new Exception("key is null.");
      }

      FileOutputStream fos = 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
      fos.write(key.getEncoded());

      fos.close();

    } catch (Exception e) {
      System.err.println("SaveEncodedKey: Exception " + e.toString());
    }
  }

  static RSAPrivateKey LoadPrivateKey(String filename) {

    RSAPrivateKey key = null;

    try {

      FileInputStream fis = new FileInputStream(filename);
      byte[] b = new byte[fis.available()];
      fis.read(b);
      fis.close();

      PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(b);

      KeyFactory factory = KeyFactory.getInstance("RSA");
      key = (RSAPrivateKey) factory.generatePrivate(spec);


    } catch (Exception e) {
      System.err.println("LoadPrivateKey: " + e.toString());
    }

    return key;
  }

  static RSAPublicKey LoadPublicKey(String filename) {

    RSAPublicKey key = null;

    try {

      FileInputStream fis = new FileInputStream(filename);
      byte[] b = new byte[fis.available()];
      fis.read(b);
      fis.close();

      X509EncodedKeySpec spec = new X509EncodedKeySpec(b);

      KeyFactory factory = KeyFactory.getInstance("RSA");
      key = (RSAPublicKey) factory.generatePublic(spec);

    } catch (Exception e) {
      System.err.println("LoadPublicKey: " + e.toString());
    }

    return key;
  }

  static void PrintPrivateKey(RSAPrivateKey key) {
    try {

      if (null == key) {
        throw new Exception("key is null.");
      }

      KeyFactory factory = KeyFactory.getInstance("RSA");
      if (null != factory) {

        RSAPrivateKeySpec spec =
              factory.getKeySpec(key, RSAPrivateKeySpec.class);

        if (null != spec) {
          System.out.print("Private Key ");
          System.out.println("(" + key.getFormat() + ")");
          System.out.println(" d: " + spec.getPrivateExponent());
          System.out.println(" n: " + spec.getModulus());

          System.out.println();
        }
      }
    } catch (Exception e) {
      System.err.println("PrintPrivateKey: " + e.toString());
    }
  }

  static void PrintPublicKey(RSAPublicKey key) {
    try {

      if (null == key) {
        throw new Exception("key is null.");
      }

      KeyFactory factory = KeyFactory.getInstance("RSA");
      if (null != factory) {
        RSAPublicKeySpec spec =
              factory.getKeySpec(key, RSAPublicKeySpec.class);

        if (null != spec) {
          System.out.print("Public Key ");
          System.out.println("(" + key.getFormat() + ")");
          System.out.println(" e: " + spec.getPublicExponent());
          System.out.println(" n: " + spec.getModulus());

          System.out.println();
        }
      }
    } catch (Exception e) {
      System.err.println("PrintPublicKey: " + e.toString());
    }
  }

  static String FormatBytes(byte[] b) {
    return FormatBytes(b, 8);
  }

  static String FormatBytes(byte[] b, int lineBreakAt) {

    StringBuilder sb = new StringBuilder();

    try {
      for (int i = 0; i < b.length; i++) {

        if (0 != i && 0 == i % lineBreakAt) {
          sb.append("\n");
        }

        sb.append(String.format("0x%02X, ", b[i]));
      }

      // Remove trailing ','
      if (sb.length() >= 2) {
        if (',' == sb.charAt(sb.length() - 2)) {
          sb.delete(sb.length() - 2, sb.length() - 1);
        }
      }
    } catch (Exception e) {
      System.err.println("FormatBytes: " + e.toString());
    }

    return sb.toString();
  }
}

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)

Share

About the Author

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

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160426.1 | Last Updated 20 Oct 2009
Article Copyright 2008 by Jeffrey Walton
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid