Signing file with hardware token

1.2k views Asked by At

I'm trying to sign some files with SafeNet eToken5110. I have managed to get certificate from it but found out that i can't export PrivateKey. I developed some code to encrypt/decrypt files with common certificate, now my issue is to do the same with eToken. But i can't find any info how to do that. Any tips? Is there any API for that? (and documentation/examples)

2

There are 2 answers

1
Дима Довг On BEST ANSWER

Ok, I've found out how to sign smtx with hardware token, and I hope someone will find it usefull. Need to use Signature class and SunPKCS11 provider

public static byte[] sign(byte[] file) throws Exception {

    char password[] = "12345678".toCharArray();
    Provider userProvider = new sun.security.pkcs11.SunPKCS11("C:\\ForJava\\eToken.cfg");
    KeyStore ks = KeyStore.getInstance("PKCS11", userProvider);
    ks.load(null, password);   

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    Security.addProvider(userProvider);

    //Working only with the first alias on the token
    String alias = (String)ks.aliases().nextElement();

    Signature signature = Signature.getInstance("SHA256withRSA"); 
    PrivateKey privateKey = (PrivateKey) ks.getKey(alias, password);
    signature.initSign(privateKey);
    signature.update(file);

    byte[] result = signature.sign();
    //System.out.println("result coding: \n" +new BASE64Encoder().encode(result));
    return result;
}

To verify signed data u can use the following code

public static void verify(byte[] sig, byte[] original) throws Exception {

    Keystore keystore = initKeystore();
    PublicKey key = keystore.getCertificate(getCertAlias()).getPublicKey();
    Signature s = Signature.getInstance("SHA256withRSA");
    s.initVerify(key);
    s.update(original);

    if ( ! s.verify(sig)) {
        System.out.println("Signature check FAILED");
        return;
    }
    System.out.println("Signature check PASSED");


}
0
vksharma On

Please add initKeysStore() method into it. It will be more useful then.