Created
February 2, 2020 08:59
-
-
Save supunsandeeptha/b4e850dd427cbac66293ba5750ee58d1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.security.*; | |
import sun.security.pkcs11.*; | |
import javax.crypto.*; | |
import javax.crypto.spec.SecretKeySpec; | |
public class SoftHSM { | |
public static void main(String[] args) throws Exception { | |
// Set up the Sun PKCS 11 provider // using the configuration file name | |
String configName = "softhsm.cfg"; | |
Provider p = new SunPKCS11(configName); | |
// exception handling | |
if (-1 == Security.addProvider(p)) { | |
throw new RuntimeException("could not add security provider"); | |
} | |
// Load the key store // using User Pin given when initializing the token | |
char[] pin = "1234".toCharArray(); | |
KeyStore keyStore = KeyStore.getInstance("PKCS11", p); | |
keyStore.load(null, pin); | |
// AES key | |
SecretKeySpec secretKeySpec = new SecretKeySpec("0123456789ABCDEF".getBytes(), "AES"); | |
Key key = new SecretKeySpec(secretKeySpec.getEncoded(), "AES"); | |
// Inserting the key in to the SoftHSM | |
keyStore.setKeyEntry("AA", key, "1234".toCharArray(), null); | |
keyStore.store(null); | |
// Retrieving the Secret Key Stored | |
SecretKey key1 = (SecretKey) keyStore.getKey("AA", "1234".toCharArray()); | |
// Test Printing the Key Retrieved | |
System.out.println(key1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment