0

I need to encrypt the data using public key located in Safenet HSM Luna SA device and also need to decrypt the data using private key which also located in HSM device in JAVA.

I'm completely new to the HSM device. I have encrypted/ decrypted data using keys which are located in epass e-token device as follows:

   private void loadKeys() {

    logger.info("In loadKeys method at "+new Date());
    try {
        char password[] = hsmServiceAppProps.getDigiSigPfxPassword().toCharArray();
        Provider userProvider = new sun.security.pkcs11.SunPKCS11(this.getClass().getClassLoader().getResourceAsStream("/pkcs11.cfg"));
        Security.addProvider(userProvider);
        KeyStore ks = KeyStore.getInstance("PKCS11");
        ks.load(null, password);

        String alias = null;
        /*X509Certificate userCert = null;
        PrivateKey userCertPrivKey = null;
        PublicKey userCertPubKey = null;
        Enumeration<String> e = ks.aliases();
        while (e.hasMoreElements()) {
            alias = (String) e.nextElement();
            logger.info("Alias of the e-Token : " + alias);
            userCert = (X509Certificate) ks.getCertificate(alias);
            userCertPubKey = (PublicKey) ks.getCertificate(alias).getPublicKey();
            userCertPrivKey = (PrivateKey) ks.getKey(alias, password);
        }*/
        alias = "*************************************";

        //X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
        publicKey = (PublicKey) ks.getCertificate(alias).getPublicKey();
        privateKey = (PrivateKey) ks.getKey(alias, password);

    } catch (Exception e) {
        logger.error("Error while getting public and private keys ->> ",e);
    }
}

private String performEncryption(String content,PublicKey publicKey) throws Exception {
    logger.debug("Encrypting using public key : "+content);
    Cipher publicEncryptCipher = Cipher.getInstance("RSA");
    publicEncryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] encryptedBinaryData = publicEncryptCipher.doFinal(content.getBytes());
    Base64 encoder = new Base64();
    String encodedEncryptedContent =  new String(encoder.encode(encryptedBinaryData),"UTF-8");
    logger.debug("Encrypted Content ->> "+encodedEncryptedContent);
    return encodedEncryptedContent;
}

private String performDecryption(String encodedEncryptedContent, PrivateKey privateKey) throws Exception {
    logger.debug("Decrypting with private key ->> "+encodedEncryptedContent);
    Base64 decoder = new Base64();
    byte[] encryptedString = decoder.decode(encodedEncryptedContent.getBytes());
    Cipher privateDecryptCipher = Cipher.getInstance("RSA");
    privateDecryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
    byte[] decryptedBinaryData = privateDecryptCipher.doFinal(encryptedString);
    String decryptedContent = new String(decryptedBinaryData,"UTF-8");
    logger.debug("Decrypted Content ->> "+decryptedContent);
    return decryptedContent;
}

In the same way I need to do encryption/decryption using HSM device. I have installed Luna client software and imported keys to the HSM device.

Could any one please help me

pooja
  • 1
  • 1
  • 3
  • Presuming your HSM is a PKCS#11 device you just need to reconfigure the configuration file that is loaded. What have you tried? – Maarten Bodewes Nov 29 '17 at 16:19

2 Answers2

0

Once you have successfully installed Luna client. you can use use either Luna JSP or JCProv libraries to perform cryptographic operation on HSM by using keys residing on HSM. To check if Luna client is installed and registered with the remote HSM correctly, you can run the following command: "VTL.exe verify" from your luna client directory. Output of successfully VTL verify

Here is an example of Encryption and Decryption using public and private keys of RSA.

 void asymetricEncDec(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE hPublicKey,
                          CK_OBJECT_HANDLE hPrivateKey)
{
    //session - handle to an open session
    //hPublicKey - handle to public asymetric key to use for encryption
    //hPrivateKey - handle to private asymetric key to use for decryption

    String startString = "this is 16 bytes";
    byte[] plainText = startString.getBytes();
    byte[] cipherText = null;
    LongRef lRefEnc = new LongRef();
    LongRef lRefDec = new LongRef();

    //mechanism to use
    CK_MECHANISM mechanism = new CK_MECHANISM(CKM.RSA_PKCS);

    /* get ready to encrypt */
    CryptokiEx.C_EncryptInit(session, mechanism, hPublicKey);

    /* get the size of the cipher text */
    CryptokiEx.C_Encrypt(session, plainText, plainText.length, null,
            lRefEnc);

    /* allocate space */
    cipherText = new byte[(int)lRefEnc.value];

    /* encrypt */
    CryptokiEx.C_Encrypt(session, plainText, plainText.length, cipherText,
            lRefEnc);

    /* get ready to decrypt */
    CryptokiEx.C_DecryptInit(session, mechanism, hPrivateKey);

    /* get the size of the plain text */
    CryptokiEx.C_Decrypt(session, cipherText, lRefEnc.value, null, lRefDec);

    /* allocate space */
    plainText = new byte[(int)lRefDec.value];

    /* decrypt */
    CryptokiEx.C_Decrypt(session, cipherText, lRefEnc.value, plainText,
            lRefDec);

    /* make sure that we end up with what we started with */
    String endString = new String(plainText, 0, (int)lRefDec.value);

    if (startString.compareTo(endString) == 0)
    {
        println("Decrypted string matches original string - hurray");
    }
    else
    {
        println("Decrypted string does not match original string - boo");
    }
}

This example is using JCProv library provided by luna client. Note: JCProv lower level library close to the 'C' implementation of PKCS#11.

0

You can also use the IAIK PKCS#11 wrapper to make all kinds of operations on the HSM. The wrapper is open source. It is well documented and working code examples are available.

Ref: https://jce.iaik.tugraz.at/products/core-crypto-toolkits/pkcs11-wrapper/