Java tutorial
/* * HSM Proxy Project. * Copyright (C) 2013 FedICT. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version * 3.0 as published by the Free Software Foundation. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, see * http://www.gnu.org/licenses/. */ package test.integ.be.fedict.hsm; import java.io.File; import java.io.FileOutputStream; import java.io.PrintWriter; import java.security.KeyStore; import java.security.PrivateKey; import java.security.Security; import java.security.Signature; import java.util.Enumeration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; import sun.security.pkcs11.SunPKCS11; public class PKCS11Test { private static final Log LOG = LogFactory.getLog(PKCS11Test.class); @Test public void testEToken() throws Exception { File tmpConfigFile = File.createTempFile("pkcs11-", ".conf"); tmpConfigFile.deleteOnExit(); PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile)); configWriter.println("name=test"); configWriter.println("library=/usr/lib/libeTPkcs11.so"); configWriter.println("slotListIndex=0"); configWriter.close(); SunPKCS11 sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath()); Security.addProvider(sunPKCS11); Security.removeProvider(sunPKCS11.getName()); sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath()); Security.addProvider(sunPKCS11); Security.removeProvider(sunPKCS11.getName()); sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath()); Security.addProvider(sunPKCS11); Security.removeProvider(sunPKCS11.getName()); sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath()); Security.addProvider(sunPKCS11); Security.removeProvider(sunPKCS11.getName()); sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath()); Security.addProvider(sunPKCS11); KeyStore keyStore = KeyStore.getInstance("PKCS11", sunPKCS11); keyStore.load(null, "HSMProxy1234".toCharArray()); Enumeration<String> aliasesEnum = keyStore.aliases(); String alias = aliasesEnum.nextElement(); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, "HSMProxy1234".toCharArray()); final int TEST_COUNT = 50; int count = TEST_COUNT; while (count > 0) { Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(privateKey); signature.update("to be signed".getBytes()); signature.sign(); count--; } } }