Showing posts with label PrivateKey. Show all posts
Showing posts with label PrivateKey. Show all posts

Wednesday, April 1, 2015

Create CMS Signature using Bouncy Castle

P
This post today will show you guys how to generate Cryptographic Message Syntax (CMS) signature. CMS is the IETF's standard for cryptographically protected messages. It can be used to digitally sign, digest, authenticate or encrypt any form of digital data. CMS is based on the syntax of PKCS#7 standard.
In this tutorial, I will use Bouncy Castle (BC) library. BC is a strong cryptographic library in Java, it has enough API to do this. The version of BC I am going to use is 1.47, you can download and use this version or higher at bouncycastle.org.

Keystore is used in this post is in PKCS#12 format

String passwordP12 = "p12KeystorePass";
String pathToP12 = "/path/to/your.p12";

OK, there is complete sample

package com.it4shared.pkcs7;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

import javax.xml.bind.DatatypeConverter;

import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.CMSTypedData;
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.bouncycastle.util.Store;
import org.bouncycastle.util.encoders.Base64;

public final class PKCS7Signer {

    public PKCS7Signer() {
    }

    public KeyStore loadKeyStore(String path, String password) throws Exception {

        KeyStore keystore = KeyStore.getInstance("PKCS12");
        InputStream is = new FileInputStream(path);
        keystore.load(is, password.toCharArray());
        return keystore;
    }

    public CMSSignedDataGenerator setUpProvider(final KeyStore keystore, String pkcs12Password, String algorithm) throws Exception {
     
     Enumeration e = keystore.aliases();
     String aliasName="";
        while(e.hasMoreElements())
        {
         aliasName = e.nextElement().toString();
        }
     
     Security.addProvider(new BouncyCastleProvider());

        Certificate[] certchain = (Certificate[]) keystore.getCertificateChain(aliasName);
        
        final List certlist = new ArrayList();

        for (int i = 0, length = certchain == null ? 0 : certchain.length; i < length; i++) {
            certlist.add(certchain[i]);
        }

        Store certstore = new JcaCertStore(certlist);

        Certificate cert = keystore.getCertificate(aliasName);
        
        ContentSigner signer = new JcaContentSignerBuilder(algorithm).setProvider("BC").
                build((PrivateKey)(keystore.getKey(aliasName, pkcs12Password.toCharArray())));
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

        generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").
                build()).build(signer, (X509Certificate) cert));

        generator.addCertificates(certstore);

        return generator;
    }

    public String SignData(final byte[] content, final CMSSignedDataGenerator generator) throws Exception {

        CMSTypedData cmsdata = new CMSProcessableByteArray(content);
        CMSSignedData signeddata = generator.generate(cmsdata, true);
        return new String(Base64.encode(signeddata.getEncoded()));
    }

    public static void main(String[] args) throws Exception {
        String passwordP12 = "p12KeystorePass";
        String pathToP12 = "/path/to/your.p12";
        String algorithm = "SHA1withRSA";
        
        PKCS7Signer signer = new PKCS7Signer();
        KeyStore keyStore = signer.loadKeyStore(pathToP12, passwordP12);
        
        CMSSignedDataGenerator signatureGenerator = signer.setUpProvider(keyStore, passwordP12, algorithm);
        String content = "signdata";
        String signedData = signer.SignData(content.getBytes("UTF-8"), signatureGenerator);
        System.out.println(signedData);
    }
To create detached signature
CMSSignedData signeddata = generator.generate(cmsdata, false);
Output:
MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIAwggXnMIIDz6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24gQXV0aG9yaXR5AhBUAUaOqeOECSoJbx0JktP7MAkGBSsOAwIaBQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0xNTA0MDExNTE5MDhaMCMGCSqGSIb3DQEJBDEWBBRwCR6OXkUq2jgegMlAi7p84cfDqzANBgkqhkiG9w0BAQEFAASBgBdoX52mvjCJKldJSp2Wy6hcTIrrr8ecnNgWuyxz+uhDEGXv/eo3/iiZozj3S992HJcWSUeCyB3aR4eYpQVGS/QZ/qPy6xRI7TJUJFsKchrr+WlI6zxxAF288GOgnXk+Ro4kpJqen4zgUYwGNnfNi5LH9QZZviC/QUSf7FOyY7OBAAAAAAAA

Saturday, March 28, 2015

Create PKCS#1 Signature in Java

PIn cryptography, PKCS #1 is the first of a family of standards called Public-Key Cryptography Standards (PKCS), published by RSA Laboratories. It provides the basic definitions of and recommendations for implementing the RSA algorithm for public-key cryptography. It defines the mathematical properties of public and private keys, primitive operations for encryption and signatures, secure cryptographic schemes, and related ASN.1 syntax representations. This article will show you how to create PKCS#1 signature in Java.

What will we do?

  1. Generate Public Key and Private Key. In further post, I will show you how to use exiting  KeyPair from P12 Keystore or Security Device (token)
  2. Generate Signature base on Private Key.
  3. Verify Signature base on Public Key.

Sample
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair keypair = keyGen.generateKeyPair();
PublicKey publicKey = keypair.getPublic();
PrivateKey privateKey = keypair.getPrivate();

String dataTobeSign = "Hello World";
// Sign message
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initSign(privateKey);
sig.update(dataTobeSign.getBytes());
byte[] signature = sig.sign();
System.out.println("Signature: "+DatatypeConverter.printBase64Binary(signature));

// Verify signature
sig.initVerify(publicKey);
sig.update(dataTobeSign.getBytes());
boolean isValid = sig.verify(signature);

System.out.println("Signature valid: "+isValid);
Output
Signature: tBxs0axyMQg5SUyledKJAWfXStrigUJr2E0nELgoUqHkLGKVYZuBM0roU0lbzU3oM1OEU6Y70ZPvlnLjQ84DErKkC4IzqfIS02TbPVyr3k3zAgp+hqkyIci30PdQviWTO2RSyx/8IBhG3z5fnHHIdrdbP9kB3ceCHcxJgjlhYLo=
Signature valid: true
This sample above using SHA1withRSA algorithm for signature. You can refer the table below to use others algorithms

Algorithm Name Description
NONEwithRSA The RSA signature algorithm, which does not use a digesting algorithm (for example, MD5/SHA1) before performing the RSA operation. For more information about the RSA Signature algorithms, see PKCS #1.
MD2withRSA
MD5withRSA
The MD2/MD5 with RSA Encryption signature algorithm, which uses the MD2/MD5 digest algorithm and RSA to create and verify RSA digital signatures as defined in PKCS #1.
SHA1withRSA SHA256withRSA
SHA384withRSA
SHA512withRSA
The signature algorithm with SHA-* and the RSA encryption algorithm as defined in the OSI Interoperability Workshop, using the padding conventions described in PKCS #1.
NONEwithDSA The Digital Signature Algorithm as defined in FIPS PUB 186-2. The data must be exactly 20 bytes in length. This algorithm is also known as rawDSA.
SHA1withDSA The DSA with SHA-1 signature algorithm, which uses the SHA-1 digest algorithm and DSA to create and verify DSA digital signatures as defined in FIPS PUB 186.
NONEwithECDSA
SHA1withECDSA
SHA256withECDSA
SHA384withECDSA
SHA512withECDSA
(ECDSA)
The ECDSA signature algorithms as defined in ANSI X9.62.
Note:"ECDSA" is an ambiguous name for the "SHA1withECDSA" algorithm and should not be used. The formal name "SHA1withECDSA" should be used instead.
with Use this to form a name for a signature algorithm with a particular message digest (such as MD2 or MD5) and algorithm (such as RSA or DSA), just as was done for the explicitly defined standard names in this section (MD2withRSA, and so on).
For the new signature schemes defined in PKCS #1 v 2.0, for which the with form is insufficient, withand can be used to form a name. Here, should be replaced by a mask generation function such as MGF1. Example: MD5withRSAandMGF1.
NOTE: The algorithm uses for generating keys must be the algorithm use for creating signature. For instance:
You use RSA algorithm to generate keys
KeyPairGenerator.getInstance("RSA")
You must use RSA algorithm for creating signature.
Signature.getInstance("SHA1withRSA")
You use DSA algorithm to generate keys
KeyPairGenerator.getInstance("DSA")
You must use RSA algorithm for creating signature.
Signature.getInstance("SHA1withDSA")
Reference

Tuesday, March 24, 2015

Generate CSR in Java

PA CSR or Certificate Signing Request is a block of encrypted text that is generated on the server that the certificate will be used on. It contains information that will be included in your certificate such as your organization name, common name (domain name), locality, and country. It also contains the public key that will be included in your certificate. A private key is usually created at the same time that you create the CSR.

A certificate authority will use a CSR to create your SSL certificate, but it does not need your private key. You need to keep your private key secret. What is a CSR and private key good for if someone else can potentially read your communications? The certificate created with a particular CSR will only work with the private key that was generated with it. So if you lose the private key, the certificate will no longer work.

This article will show you how to generate CSR in Java.

What will we do?

  • Generate Keypair to obtain the Private Key and Public Key.
  • Package the necessary information for CSR and use Private Key sign on it. 

Coding time

package com.it4shared.gencsr;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
 
import sun.security.pkcs.PKCS10;
import sun.security.x509.X500Name;
import sun.security.x509.X500Signer;
 
/**
 * This class generates PKCS10 certificate signing request
 *
 * @author Pankaj@JournalDev.com
 * @version 1.0
 */
public class GenerateCSR {
    private static PublicKey publicKey = null;
    private static PrivateKey privateKey = null;
    private static KeyPairGenerator keyGen = null;
    private static GenerateCSR gcsr = null;
 
    private GenerateCSR() {
        try {
            keyGen = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        keyGen.initialize(2048, new SecureRandom());
        KeyPair keypair = keyGen.generateKeyPair();
        publicKey = keypair.getPublic();
        privateKey = keypair.getPrivate();
    }
 
    public static GenerateCSR getInstance() {
        if (gcsr == null)
            gcsr = new GenerateCSR();
        return gcsr;
    }
 
    public String getCSR(String cn) throws Exception {
        byte[] csr = generatePKCS10(cn, "Java", "Java tutorial", "it-shared.com",
                "California", "US");
        return new String(csr);
    }
 
    /**
     *
     * @param CN
     *            Common Name, is X.509 speak for the name that distinguishes
     *            the Certificate best, and ties it to your Organization
     * @param OU
     *            Organizational unit
     * @param O
     *            Organization NAME
     * @param L
     *            Location
     * @param S
     *            State
     * @param C
     *            Country
     * @return
     * @throws Exception
     */
    private static byte[] generatePKCS10(String CN, String OU, String O,
            String L, String S, String C) throws Exception {
        // generate PKCS10 certificate request
        String sigAlg = "SHA1WithRSA";
        PKCS10 pkcs10 = new PKCS10(publicKey);
        Signature signature = Signature.getInstance(sigAlg);
        signature.initSign(privateKey);
        // common, orgUnit, org, locality, state, country
        X500Name x500Name = new X500Name(CN, OU, O, L, S, C);
        pkcs10.encodeAndSign(new X500Signer(signature, x500Name));
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bs);
        pkcs10.print(ps);
        byte[] c = bs.toByteArray();
        try {
            if (ps != null)
                ps.close();
            if (bs != null)
                bs.close();
        } catch (Throwable th) {
        }
        return c;
    }
 
    public PublicKey getPublicKey() {
        return publicKey;
    }
 
    public PrivateKey getPrivateKey() {
        return privateKey;
    }
 
    public static void main(String[] args) throws Exception {
        GenerateCSR gcsr = GenerateCSR.getInstance();
 
        System.out.println("Public Key:\n"+gcsr.getPublicKey().toString());
 
        System.out.println("Private Key:\n"+gcsr.getPrivateKey().toString());
        String csr = gcsr.getCSR("it-4shared.com ");
        System.out.println("CSR Request Generated!!");
        System.out.println(csr);
    }
 
}
Which JRE version are you using?

A little bit different between jre 6 and jre 7 when you compile above source code.
If you use jre 7, you will meet error at line 80. So, need to be change likes that

pkcs10.encodeAndSign(x500Name, signature);

Access restriction?

If you meet this error
Access restriction on class due to restriction on required library rt.jar

Don't worry, follow this post will solve your doubt: How to use security token with SunPKCS11
Result:
Public Key:
Sun RSA public key, 2048 bits
  modulus: 19257207091825903467956315158723391899488308330132045583200286325612347332535086558206008961138104081229683751617734086462108005404147757373221546303174073782221524624663743733137293118804642576754211011016378744661501795576358879760626588692993482180681014044406521310609536437986345390932449865696305113759679659525664537209643897958780342733357237621431519275520146740782091893974820651212176881168551585627815201259935642909620627195097406549992857927603700719938530129507093704988311911587466889622586204313257180129127988524875791234151024204084557862706777473491496315685690849452176875303556203545098513831973
  public exponent: 65537
Private Key:
Sun RSA private CRT key, 2048 bits
  modulus:          19257207091825903467956315158723391899488308330132045583200286325612347332535086558206008961138104081229683751617734086462108005404147757373221546303174073782221524624663743733137293118804642576754211011016378744661501795576358879760626588692993482180681014044406521310609536437986345390932449865696305113759679659525664537209643897958780342733357237621431519275520146740782091893974820651212176881168551585627815201259935642909620627195097406549992857927603700719938530129507093704988311911587466889622586204313257180129127988524875791234151024204084557862706777473491496315685690849452176875303556203545098513831973
  public exponent:  65537
  private exponent: 2783813418190619183902499806426070995861150695327387580378099587238527528395218121861600758317017838252743089595593523279094423656848739694430641159593377405324728386927450266685120084952853865330567391219756354836551383360398309761694558818338041872221370020853981459278190155385242477282970383563586899732311853899623497405928076441517903760180474928793248628828754448487336682275751051021838961212440307381068644851436310421836191225424578775215867826169004445462764062481676308203696424556266358858686201176880163788253425032797395259659903439818757113893472931375810785783487361222830419073932373897048442536449
  prime p:          169794671408511140392706269775175031159390685459349906887729057952716762533744955941051283491433241967732738235159355343037708649379582253614206344883522591412008437870183780071400873398090675229391111420031401568118685947628077228009448051722575942234847218706313259375157623859724980789891716857192612053569
  prime q:          113414672746088398541001088650633320632743979636605152087127384062794579793841514268564905152345235697965534839365534335014577365577374730057949690843669331577696658613728564272446970620869948769201260665107212570850476698585808461247012954620596552809218042036976230482750748026414616188954122734890936767717
  prime exponent p: 83269004365008286192861734754018729900099434375444497114173854808738830703794236598339689815137470388374966917588868589121137006440022790655058851100239804812273237913662613355735295650008915602981984543689965155550827263328599144120476377959985821496681105470511438673078810913706164191023693177749523954433
  prime exponent q: 53079250537376189939264619849737174579970449416573130061131439095076603314718509020025676653382563579779344257335851032600929504813910275422088788280773086014787248622919610652982185374419382465613944292844781176634966832461417475981024174803896081110889051762487372650059217594125289649321770183630236546369
  crt coefficient:  22627559854384748872439261257649913611260962127344877457040949619018920842555330549405771343927369179585682405889416290866910114525013884822425546833852118939372215521341257434019929228915416662897809396503272657439129844461902188812667165357101583442000219847545758625783360809746708638229828638100188254455
CSR Request Generated!!
-----BEGIN NEW CERTIFICATE REQUEST-----
MIIC3DCCAcQCAQAwgZYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH
Ew1pdC1zaGFyZWQuY29tMRYwFAYDVQQKEw1KYXZhIHR1dG9yaWFsMQ0wCwYDVQQLEwRKYXZhMTMw
MQYDVQQDDCppdC00c2hhcmVkLmNvbSA8aHR0cDovL3d3dy5pdC00c2hhcmVkLmNvbT4wggEiMA0G
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCYi+UW7iENy/lKoqSb5VQBcaKB2+0mGsFnDJcc3ZPF
eFLP60Tol1y9lH4yiUAz4zQgEODBf/jQP21P+rxTcLlniYp+NIohhKNkSDK4fIWhejCh4RRsntsL
1hehYcgwQcEuHN2HkyEpboCTvpY/72D/KNc3lWk2KggNCrdpD/+V9q91dC/QsQF/SEKT1FY6/3Z5
y9swRuuSD6vuwhL078Flu1kdnJ9PDwUE6D7Gz4cI5gAZYiRDy8ZgbIbcjpY/MP5LdWoDjWD8RubR
MI7y+3dRJks6jg7vf2AIsQWXGf7mUgn7To+ugM/86TagZhJEUEy7bvYuIoEQ0/M18AokQFglAgMB
AAGgADANBgkqhkiG9w0BAQUFAAOCAQEAeT5+X9jRPEB6JeUkO6Td4Vul/bOZW0RfkITyy38zsOYU
dMa+eigZ+ta3qQU6W9AE0qFh6V8Vb1BbDeMukK4c/tKKyybIuu7kyJ7reZeEN3jzSVP3uh1V/qmH
DpiINOB4nz9ty/5rSN8VR4xlk8iSzucW3E6fe4sqb8ZVxpQiSZHfvTBnJ17dFbE1bae61rL9uIqc
53ixbg/bRkC26bjvEHBYiJeAsyszh7Xo5Vks93JwKgCW+X2ano+DwUtJsO0Gjiwbbv6tjuE1/s+n
bn7+4c8h3P+QU5c7J85E5NfkQsfJzVap0jJxdL0O76a+e5UOjSwhbvGDSq18PQZZo8fm5A==
-----END NEW CERTIFICATE REQUEST-----
You can copy CSR part and verify it at site: https://www.sslshopper.com/csr-decoder.html

Wednesday, March 4, 2015

How to use security token with SunPKCS11


What is the Security token?


A security token (or sometimes a hardware token, authentication token, USB token, cryptographic token, software token, virtual token, or key fob) may be a physical device that an authorized user of computer services is given to ease authentication. The term may also refer to software tokens.

Security tokens are used to prove one's identity electronically (as in the case of a customer trying to access their bank account). The token is used in addition to or in place of a password to prove that the customer is who they claim to be. The token acts like an electronic key to access something.

Some may store cryptographic keys, such as a digital signature, or biometric data, such as fingerprint minutiae. Some designs feature tamper resistant packaging, while others may include small keypads to allow entry of a PIN or a simple button to start a generating routine with some display capability to show a generated key number. Special designs include a USB connector, RFID functions or Bluetooth wireless interface to enable transfer of a generated key number sequence to a client system.

In this post, USB token is mentioned and it is usually used for document signing, data signing, data encryption...Java supports many objects, classes to solve security problems (digital signature, encryption/decryption, authentication...). Today, I will show you how to use SunPKCS11 java class with USB Token.


package com.it4shared.pkcs11demo;

import java.io.ByteArrayInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

public class PKCS11Demo {
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  try {
   // PKCS#11 Module
   String pkcs11Module = "C:/Windows/System32/viettel-ca_v4.dll";
   // Define your slot of device
   int slotId = 1;
   // PIN code protects keypair on device
   String pinCode = "viettel-ca";
   
   UUID uuid = UUID.randomUUID();
   String aliasKey = "";
   String configValue = "name = PROVIDER" + uuid.toString() + "\r\nlibrary = " + pkcs11Module + "\r\nslot = " + slotId + "\r\ndisabledMechanisms={ CKM_SHA1_RSA_PKCS }\r\n";
   Provider p = new sun.security.pkcs11.SunPKCS11(new ByteArrayInputStream(configValue.getBytes()));
         Security.addProvider(p);
         KeyStore keystore = null;
         keystore = KeyStore.getInstance("PKCS11", p);
         keystore.load(null, pinCode.toCharArray());
         
         Enumeration aliases = keystore.aliases();
         
         List listKey = new ArrayList();
         while(aliases.hasMoreElements()) {
          aliasKey = aliases.nextElement();
          System.out.println(aliasKey);
         }
         // Get PrivateKey
         PrivateKey privateKey = (PrivateKey) keystore.getKey(aliasKey, pinCode.toCharArray());
         // Get Certificate
         X509Certificate x509Cert = (X509Certificate) keystore.getCertificate(aliasKey);
         // Get PublicKey
         PublicKey publicKey = x509Cert.getPublicKey();
         
         
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}

You have been gotten 3 objects PrivateKey, PublicKey and X509Certificate. These objects are important if you want to some security issues such as data signing, documents signing, data encryption/decryption...
In the further post, I will show you how to do them in Java.

NOTE: If you get this error

Access restriction: The constructor SunPKCS11(InputStream) is not accessible due to restriction on required library C:\Program Files (x86)\Java\jre6\lib\ext\sunpkcs11.jar
Don't worry, just follow these steps:
In Eclipse, choose your project and right click and open Properties dialog for this project. Select "Java Build Path" in left column, remove the current JRE System Library.


Then, select "Add Library".


Select "JRE System Library" and click Next


Click Finish to close dialog.


And select OK to complete.

After complete these steps above, you may not meet this error any more.