PKCS#11 provider - ECDSA key pair generation on token

Hello,
I want to generate ECDSA key pair on HSM (nCipher's netHSM) using SunPKCS11 provider and Java 6.
After generation for all supported curve names (e.g. secp256r1) I try to call getEncoding method from PublicKey object (keyPair.getPublic().getEncoded()) and
I get RuntimeException
caused by java.io.IOException: "Point does not match field size"
at sun.security.ec.ECParameters.decodePoint(ECParameters.java:75)
at sun.security.pkcs11.P11ECKeyFactory.decodePoint(P11ECKeyFactory.java:61)
at sun.security.pkcs11.P11Key$P11ECPublicKey.fetchValues(P11Key.java:1002)
Keys are accessible on HSM.
Everything is well configured and works fine with RSA keys.
Using IAIK PKCS#11 provider I got proper values. Is it any bug in SunPKCS11 provider?
Regards,
MarcinP

I recently had a problem with ECDSA and the PKCS#11 library of nCipher. Here's info from one of their engineers about the PKCS11 library:
"There are two separate issues - one is that our current pkcs11
release doesn't support ECDSA signature with SHA-2 hashes
(the v11.00 firmware adds support for it, but the main release version of
the pkcs11 library hasn't been updated to take advantage of it yet).
There is a hotfix version that does support SHA-2 hashes with some
restrictions, talk to [email protected] for details, and V11.10
should be out soon and have that merged in.
But the issue with setting CKA_SIGN is that our underlying HSM API
allows elliptic curve keys to be either key exchange (ECDH) or
signature (ECDSA) keys, but not both at one.
At the PKCS #11 level, if you specify CKA_DERIVE=true and let
CKA_SIGN default, it will default to false, and vice versa.
If you specify both CKA_DERIVE=true and CKA_SIGN=true, then we
return CKR_TEMPLATE_INCONSISTENT because we can't do both with
the same key. (However, the tests using C_GetMechanismInfo will
show that we can do both mechanisms, because we can - so long
as you use different keys, even though they have the same PKCS#11
type.)
I can't comment on when or how that will be changed."
I was using the PKCS#11 library through NSS when I ran into the problem, but I imagine Java would run into similar problems also using the PKCS#11 library. I was able to generate keypairs but not create a CSR (which required making a signature, which required SHA-2).
Can you just use the java classes to speak to the netHSM? I've never directly written code to do so myself, but I have used Corestreet's OCSP product that uses the java classes to speak to the nCipher HSMs (though not using EC). It might work better than going through the PKCS#11 layer. There should be a java directory under NFAST_HOME that contains some jars.
Please post back if you figure anything out as I'll probably be playing with this stuff myself soon.
Dave

Similar Messages

  • ECDSA KEY PAIR

    Hi,
    does this output look ok? a lot of sequences, prefix and in the middle of the sequence repeat every generation.
    thanks (output and partial code below)
    pub: 3049301306072a8648ce3d020106082a8648ce3d030101033200046b4c88bb2a2b05ab1de3e91780a00849f2e2594fcfd5d9b139f5e0a836b4028ccfa4a83bc0f9e9d2a268a036d2844c49
    priv:
    3039020100301306072a8648ce3d020106082a8648ce3d030101041f301d02010104181158c20db4dd65855948a11cd73b2f8d4dbbcebddee029a7
    pub: 3049301306072a8648ce3d020106082a8648ce3d030101033200045efbaecaa5cee746916a11beaf457c8b905814a8597521b4c47f0c9df4d9709e4f2a84f048012babacef109e5e8a54ec
    priv:
    303a020100301306072a8648ce3d020106082a8648ce3d0301010420301e020101041900f0f11adf664150a930f8bc6fe2e5fd5d534af124e9e9000f
    code:
    algorithm is input by the user, in this case "ECDSA".
                            // Gen. keys for ECDSA\other with FLEXIPROVIDER.
                   KeyPairGenerator generate = KeyPairGenerator.getInstance(algorithm, "FlexiEC");
                   // Obtain a specific set of EC domain parameters (curve parameters).
                   CurveParams ecParams = new Prime192v1();
                   generate.initialize(ecParams, new SecureRandom());
                   KeyPair keyPair = generate.generateKeyPair();
                   // Write keys to separate files.
                   FileOutputStream pubFos = new FileOutputStream(publicKeyFile);
                   pubFos.write(keyPair.getPublic().getEncoded());
                   pubFos.close();
                   System.out.println("pub: " + ByteUtils.toHexString(keyPair.getPublic().getEncoded()));
                   FileOutputStream privFos = new FileOutputStream(privateKeyFile);
                   privFos.write(keyPair.getPrivate().getEncoded());
                   privFos.close();
                   System.out.println("priv: " + ByteUtils.toHexString(keyPair.getPrivate().getEncoded()));Edited by: sk16 on Apr 17, 2010 4:33 PM

    sk16 wrote:
    its seems that nothing is being written to the files.. (: only to the screenHow are you determining this? The content won't look the same as you see on the screen because the the file is written in it's raw binary form without being hex encoded.
    This does not look to a a cryptographic problem.

  • PKCS#11 Provider unable to fetch asymmetric keys and certificates

    Hi,
    I'm facing a problem while getting keys and certificate from Eracom HSM (ProtectServer Orange:38039 Model: PSO:PL50) using Sun PKCS#11 Provider. It gets only the symmetric keys but NEVER gets the asymmetric keys.
    My code snippet and configuration file are:
         Java Code:
         java.io.InputStream is = new java.io.FileInputStream("pkcs11.cfg");
    sun.security.pkcs11.SunPKCS11 pkcs11_provider = new sun.security.pkcs11.SunPKCS11(is);
    System.out.println("Provider Name : " + pkcs11_provider.getName());
    java.security.Security.addProvider(pkcs11_provider);
    KeyStore ks = KeyStore.getInstance("PKCS11", pkcs11_provider);
    ks.load(null, "password".toCharArray());
    java.util.Enumeration obj_enumeration = ks.aliases();
    while (obj_enumeration.hasMoreElements()) {
    String str_certAlias = (String) obj_enumeration.nextElement();
    System.out.println("Alias : " + str_certAlias);
         pkcs11.cfg:
         name = Eracom
         library = G:\Eracom\cryptoki.dll
         slot = 0
         attributes(*, CKO_PRIVATE_KEY, *) = {
         CKA_TOKEN = false
         CKA_SENSITIVE = false
         CKA_EXTRACTABLE = true
         CKA_DECRYPT = true
         CKA_SIGN = true
         CKA_SIGN_RECOVER = true
         CKA_UNWRAP = true
         attributes(*, CKO_PUBLIC_KEY, *) = {
         CKA_ENCRYPT = true
         CKA_VERIFY = true
         CKA_VERIFY_RECOVER = true
         CKA_WRAP = true
    I also ran my program without specifying any attributes in configuration file, also tried many other combination, but in all cases (with or without attributes) only symmetric keys are loaded from HSM. I am able to get all keys (symmteric and asymmteric) and certificates from the same HSM using IAIK PKCS#11 Provider. Though, the Sun PKCS#11 Provider is working fine with SmartCard tokens (Rainbow, Alladin etc.)
    Any help to resolve my problem would be highly appreciated.
    Thanks in advance.

    I recently had a problem with ECDSA and the PKCS#11 library of nCipher. Here's info from one of their engineers about the PKCS11 library:
    "There are two separate issues - one is that our current pkcs11
    release doesn't support ECDSA signature with SHA-2 hashes
    (the v11.00 firmware adds support for it, but the main release version of
    the pkcs11 library hasn't been updated to take advantage of it yet).
    There is a hotfix version that does support SHA-2 hashes with some
    restrictions, talk to [email protected] for details, and V11.10
    should be out soon and have that merged in.
    But the issue with setting CKA_SIGN is that our underlying HSM API
    allows elliptic curve keys to be either key exchange (ECDH) or
    signature (ECDSA) keys, but not both at one.
    At the PKCS #11 level, if you specify CKA_DERIVE=true and let
    CKA_SIGN default, it will default to false, and vice versa.
    If you specify both CKA_DERIVE=true and CKA_SIGN=true, then we
    return CKR_TEMPLATE_INCONSISTENT because we can't do both with
    the same key. (However, the tests using C_GetMechanismInfo will
    show that we can do both mechanisms, because we can - so long
    as you use different keys, even though they have the same PKCS#11
    type.)
    I can't comment on when or how that will be changed."
    I was using the PKCS#11 library through NSS when I ran into the problem, but I imagine Java would run into similar problems also using the PKCS#11 library. I was able to generate keypairs but not create a CSR (which required making a signature, which required SHA-2).
    Can you just use the java classes to speak to the netHSM? I've never directly written code to do so myself, but I have used Corestreet's OCSP product that uses the java classes to speak to the nCipher HSMs (though not using EC). It might work better than going through the PKCS#11 layer. There should be a java directory under NFAST_HOME that contains some jars.
    Please post back if you figure anything out as I'll probably be playing with this stuff myself soon.
    Dave

  • Generating key pair on PKCS#11token and save it there

    Hello,
    again i'm completely lost in this PKCS11 jungle.
    What i want to do:
    Generating key pair on crypto pkcs11 token and store it there.
    In the moment i've tried eg:
    sun.security.pkcs11.SunPKCS11 p = new sun.security.pkcs11.SunPKCS11(configName);
    Security.addProvider(p);
    Builder builder = KeyStore.Builder.newInstance("PKCS11", p, new KeyStore.CallbackHandlerProtection(new UserInputDialog(new JDialog(),"test","test")));
    KeyStore ks = builder.getKeyStore();
    ks.load(null,null);
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", p);
    gen.initialize(1024);
    KeyPair kp = gen.generateKeyPair();
               Here access to token works. The callback PIN dialog comes up and i can login.
    But i'm not sure whether the key are generated on this PKCS11. And they are not stored there.
    How i can generate keys are stored there.
    (like with keytool -genkeys ). In keytool case a certificate is stored.
    ... every little hint, also to some documentation i've not seen, is very welcome ...
    Thank You !
    Regards
    Thomas
    .

    First, you need to get a KeyStore representation of the PKCS#11 token with code similar to this, I'm using NSS as the PKCS#11 token in this example:
    Provider nss = new sun.security.pkcs11.SunPKCS11(configFile);
    Security.insertProviderAt(nss, 1);  //you may not want it at highest priority
    KeyStore ks = KeyStore.getInstance("PKCS11", nss);
    ks.load(null, password);From the testing I've done in the past with various tokens, when you generate an asymmetric keypair (e.g. RSA like you are) specifying the PKCS11 provider, it creates it right on the token automatically and code like below is not needed.
    To store the key in the keystore, use code similar to this, I'm using NSS again and storing a symmetric key:
    KeyGenerator kg = KeyGenerator.getInstance("DESede",nss);
    SecretKey tripleDesKey = kg.generateKey();
    KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(tripleDesKey);
    ks.setEntry(randAlias, skEntry, new KeyStore.PasswordProtection(password));

  • Problem with Sun PKCS#11 Provider and Ativcard smart card.

    Hi,
    I'm trying to make a signature with a smartcard.
    I have no problem signing with my card in applications such as Microsoft Office, Outlook (they probably use CAPICOM or MS CryptoAPI).
    There is only one certificate on my card with non extractable pair of keys.
    When I`m using Java based application I have the following problem:
    I have Java 1.5.0 installed, and according to the reference guide on:
    http://java.sun.com/j2se/1.5.0/docs/guide/security/p11guide.html
    I configured "Sun PKCS#11 Provider".
    In file:
    %JAVA_HOME%/lib/security/java.security I inserted the following lines:
    # Configuration for security providers 1..6 omitted
    security.provider.7=sun.security.pkcs11.SunPKCS11 C:/pkcs11.cfg
    In my case (I`m using ActivCard) The file "C:/pkcs11.cfg" contains:
    name = ActivCard
    library = c:\windows\system32\acpkcs211.dll
    After that I try tu use configured provider with keytool.exe from jsdk.
    In cmdline:
    c:\Program Files\Java\jdk1.5.0_06\bin>keytool.exe -keystore NONE -storetype PKCS11 -list
    Enter keystore password:  1111
    Keystore type: PKCS11
    Keystore provider: SunPKCS11-ActivCard
    Your keystore contains 1 entry
    Cinek's dp ID, keyEntry,
    Certificate fingerprint (MD5): 36:19:DD:01:2E:A2:C5:F6:51:44:03:74:14:D5:62:C0
    So till now everything looks ok. Certificate is accessible.
    But when I trying to use jarsigner.exe to sign something:
    c:\Program Files\Java\jdk1.5.0_06\bin>jarsigner.exe -keystore NONE -storetype PKCS11 D:\Applet.jar "Cinek's dp ID"
    Enter Passphrase for keystore: 1111
    jarsigner error: java.lang.NullPointerException
    I`ve got the java.lang.NullPointerException !
    To find reason of the exception I`ve written simple application, which signs a byte array:
    import java.security.KeyStore;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.Signature;
    import java.security.cert.Certificate;
    import java.util.Enumeration;
    public class Main {
         public static void main(String[] args) throws Exception {
              PrivateKey privkey = null;
              char[] pin = { '1', '1', '1', '1' };
              KeyStore smartCardKeyStore = KeyStore.getInstance("PKCS11");
              smartCardKeyStore.load(null, pin);
              Enumeration aliasesEnum = smartCardKeyStore.aliases();
              if (aliasesEnum.hasMoreElements()) {
                   String alias = (String) aliasesEnum.nextElement();
                   privkey = (PrivateKey) smartCardKeyStore.getKey(alias, null);
                   byte[] aDocument = new byte[100];
                   Signature signatureAlgorithm = Signature.getInstance("SHA1withRSA");
                   signatureAlgorithm.initSign(privkey);
                   signatureAlgorithm.update(aDocument);
                   byte[] digitalSignature = signatureAlgorithm.sign();
    When I`ve run this application in last line in method signatureAlgorithm.sign() I got:
    Exception in thread "main" java.lang.NullPointerException
         at java.math.BigInteger.modPow(Unknown Source)
         at sun.security.rsa.RSACore.crtCrypt(Unknown Source)
         at sun.security.rsa.RSACore.rsa(Unknown Source)
         at sun.security.rsa.RSASignature.engineSign(Unknown Source)
         at java.security.Signature$Delegate.engineSign(Unknown Source)
         at java.security.Signature.sign(Unknown Source)
         at Main.main(Main.java:31)
    In debug, before this exception variables are:
    alias= "Cinek's dp ID"
    privkey =
    SunPKCS11-ActivCard RSA private key, 1024 bits (id 192168768, token object, not sensitive, extractable)
      modulus:          112271510887039102410124262012976131016781096451891854145879061791454872222254764386718257162446565027910080375427552248069203548913907633164297672417327888344423061606707834842776634133861005271620794248782338105033496749719965719732501903618453514554701005390412127008091861831421936757053019877456102263703
      public exponent:  65537
      private exponent: null
      prime p:          null
      prime q:          null
      prime exponent p: null
      prime exponent q: null
      crt coefficient:  null
    As you can see, private key has extractable attribute set, what is wrong. Attribute is set and key has no values.
    I think that can be the reason of NullPointerException. (Maybe when extractable = true, sign() methods expects key values filled).
    So, I can not sign anything.
    I tryed to add some additional attributes to file "C:/pkcs11.cfg":
    attributes(*,CKO_PRIVATE_KEY,*) = {
      CKA_EXTRACTABLE = false
    but with no effect. Key was still extractable.
    Can you help me to solve this problem?
    PS. I`m using acpkcs211.dll (v3.2.102.0) as an implementation of PKCS#11. (Activcard says that it is PKCS#11 v2.11 implementation)
    PS2. Sorry for my english

    Can I ask you one question?
    Which driver did you specify? I mean the smarcard reader driver or the smartcard itself driver?
    If the second, does it come along with the card? because as far as I know I just got the smart card but no software at all (apart the smartcard reader driver).
    Can you help me out with this?
    thanks in advance,
    Marco

  • X.509 and PKCS#11 provider

    Sorry if I'm asking the stupid question, but there is something in JCE PKCS#11 provider architecture that I'm missing.
    Let's say I have some hardware crypto module (e.g. SUN SCA-6000) and want to be sure that all crypto work is done in it. So I would configure PKCS#11 provider as the 1st (highest priority) entry in java.security file (and configure PKCS#11 to use my hardware crypto module).
    Now, let's say I need to work with some X.509 certificate. When I check the supported algorithms of PKCS#11 and SUN providers, it looks like CertificateFactory.X509 algorithm is supported only by SUN provider, and not by PKCS#11 provider.
    http://java.sun.com/javase/6/docs/technotes/guides/security/p11guide.html#ALG
    http://java.sun.com/javase/6/docs/technotes/guides/security/SunProviders.html#SUNProvider
    So I wonder what does this essentially mean? Does it mean that even though I configured my HCM PKCS#11 provider, some crypto work is still done in other software modules (e.g. SUN provider)? Or may be SUN provider just "decomposes" these "high-level" algorithms to more "primitive" ones (e.g. Signature.SHA1withRSA) and essentially "proxies" all work to whatever provider supports these "primitive" algorithms - i.e. essentially to my HCM PKCS#11 provider?
    Regards,
    Alex

    This is not a stupid question. Any question involving cryptography isn't stupid IMO, and one that includes hardware security modules (HSM) is even less stupid. :-)
    That said, sabre150 has provided some information, and I'll try to add a little more from my experience.
    HSM's are used primarily to perform "raw" cryptographic operations in highly constrained environments for security reasons - the goal is to ensure that symmetric keys (DES, 3DES, AES) or the private-keys of asymmetric key-pairs (RSA, DSA, EC) do not come out of the HSM into the main memory of the computer. This ensure that attackers cannot snoop the secrets from main memory.
    So, the CertificateFactory in JCE is primarily used to do cryptographic operations with the digital certificate; however any operation involving just the digital certificate - and not its corresponding private-key - involves just the public-key in the certificate, the certificate attributes or certificate extensions. Since ALL information in a digital certificate is public information, there is no reason to waste HSM resources to perform X509 operations inside the security module. Not only is there nothing to protect in those operations, but as sabre150 pointed out, some old HSM's may not be able to handle them very well.
    However, some HSM's are not just for security, but they also perform crypto-acceleration. This means that they can speed up raw cryptographic processing, and there is a benefit from having them perform even the public-key operations inside the HSM. However, the PKCS11 libraries will typically send in only the "raw" crypto operation into the HSM, leaving all the certificate-parsing work outside.
    One final point: in order to make sure that you are definitely performing all secret operations inside an HSM, make sure you explicitly name the specific HSM provider for your crypto operations, otherwise the JVM may silently use a software module to perform the operation (if possible) and expose your secret in main memory.
    Hope that helps.

  • Problem working with Sun PKCS#11 provider - CKR_USER_NOT_LOGGED_IN

    Hi I was trying out the new Sun PKCS#11 provider in J2SE1.5 RC, I am not able to generate RSA certificate and store into the pkcs#11 device (HSM) keystore.
    Bellow is the command I gave
    java sun.security.tools.KeyTool -genkey -keystore NONE -storetype PKCS11 -genkey -v -alias "acs_visa_server" -keyalg "RSA" -sigalg "SHA1WithRSA" -keysize "1024" -validity "800" -dname "cn=192.168.1.1,ou=Test Technology,o=Test Ltd.,l=Test,S=Test,c=IN"
    The output is like this
    Enter keystore password: 1234
    Generating 1,024 bit RSA key pair and self-signed certificate (SHA1WithRSA)
    for: CN=192.168.1.1, OU=Test Technology, O=Test Ltd., L=Test, ST=Test, C=IN
    keytool error: java.security.KeyStoreException: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_USER_NOT_LOGGED_IN
    And is there a way to manage Private Keys i.e., store/delete/exprot to keystore using java code. Thanks in advance for the help.

    I am a developer :-), The hsm vendor has just implemented the pkcs#11 dll compliant with PKCS#11 V 2.10. And I am able to access the tokens and generate the keys using there tools written in c++.
    It looks like I need to give the user�s pin for the slot and don't know how to provide it. I even tried to do programmatically. Bellow is the code
    //--------------- main code -----
    char pin[] = "1234".toCharArray();
              KeyStore ks = KeyStore.getInstance("PKCS11", providerName);
              ks.load(null, pin);
              try {
                   MyGuiCallbackHandler mcb = new MyGuiCallbackHandler();
                   AuthProvider aprov = (AuthProvider)Security.getProvider("SunPKCS11");
                   aprov.login(null, mcb);
              } catch (Exception e) {
                   System.out.println("Error in login : "+e);
                   //return;
    String args1[] = new String[]{"-genkey", "-keystore", "NONE", "-storetype", "PKCS11",
                   "-genkey", "-v", "-alias", "cert_alias", "-keyalg", "RSA", "-sigalg", "SHA1WithRSA",
                   "-keysize", "1024", "-validity", "800", "-dname",
                   "cn=192.168.1.1,ou=test,o=test Ltd.,l=test,S=test,c=IN"};
              sun.security.tools.KeyTool.main(args1);
    //--------------- help class -----
    class MyGuiCallbackHandler implements CallbackHandler {
         public void handle(Callback[] callbacks)
                   throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
    if (callbacks[i] instanceof TextOutputCallback) {
    // display the message according to the specified type
    TextOutputCallback toc = (TextOutputCallback)callbacks;
    switch (toc.getMessageType()) {
    case TextOutputCallback.INFORMATION:
    System.out.println(toc.getMessage());
    break;
    case TextOutputCallback.ERROR:
    System.out.println("ERROR: " + toc.getMessage());
    break;
    case TextOutputCallback.WARNING:
    System.out.println("WARNING: " + toc.getMessage());
    break;
    default:
    throw new IOException("Unsupported message type: " +
    toc.getMessageType());
    } else if (callbacks[i] instanceof NameCallback) {
    // prompt the user for a username
    NameCallback nc = (NameCallback)callbacks[i];
    // ignore the provided defaultName
    System.err.print(nc.getPrompt());
    System.err.flush();
    nc.setName((new BufferedReader
    (new InputStreamReader(System.in))).readLine());
    } else if (callbacks[i] instanceof PasswordCallback) {
    // prompt the user for sensitive information
    PasswordCallback pc = (PasswordCallback)callbacks[i];
    System.err.print(pc.getPrompt());
    System.err.flush();
    pc.setPassword(readPassword(System.in));
    } else {
    throw new UnsupportedCallbackException
    (callbacks[i], "Unrecognized Callback");
         // Reads user password from given input stream.
         private char[] readPassword(InputStream in) throws IOException {
    System.out.println(:"Sending pin has 9876");
    return "9876".toCharArray();
    And this is the output
    Error in login : java.lang.NullPointerException
    Generating 1,024 bit RSA key pair and self-signed certificate (SHA1WithRSA)
    for: CN=192.168.1.1, OU=test, O=test., L=test, ST=test, C=IN
    keytool error: java.security.KeyStoreException: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_USER_NOT_LOGGED_IN
    Thanks again

  • I need help with Creating Key Pairs

    Hello,
    I need help with Creating Key Pairs, I generate key pais with aba provider, but the keys generated are not base 64.
    the class is :
    import java.io.*;
    import java.math.BigInteger;
    import java.security.*;
    import java.security.spec.*;
    import java.security.interfaces.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import au.net.aba.crypto.provider.ABAProvider;
    class CreateKeyPairs {
    private static KeyPair keyPair;
    private static KeyPairGenerator pairGenerator;
    private static PrivateKey privateKey;
    private static PublicKey publicKey;
    public static void main(String[] args) throws Exception {
    if (args.length != 2) {
    System.out.println("Usage: java CreateKeyParis public_key_file_name privete_key_file_name");
    return;
    createKeys();
    saveKey(args[0],publicKey);
    saveKey(args[1],privateKey);
    private static void createKeys() throws Exception {
    Security.addProvider(new ABAProvider());
    pairGenerator = KeyPairGenerator.getInstance("RSA","ABA");
    pairGenerator.initialize(1024, new SecureRandom());
    keyPair = pairGenerator.generateKeyPair();
    privateKey = keyPair.getPrivate();
    publicKey = keyPair.getPublic();
    private synchronized static void saveKey(String filename,PrivateKey key) throws Exception {
    ObjectOutputStream out= new ObjectOutputStream(new FileOutputStream(filename));
    out.writeObject(key);
    out.close();
    private synchronized static void saveKey(String filename,PublicKey key) throws Exception {
    ObjectOutputStream out= new ObjectOutputStream( new FileOutputStream(filename));
    out.writeObject(key);
    out.close();
    the public key is:
    �� sr com.sun.rsajca.JSA_RSAPublicKeyrC��� xr com.sun.rsajca.JS_PublicKey~5< ~��% L thePublicKeyt Lcom/sun/rsasign/p;xpsr com.sun.rsasign.anm����9�[ [ at [B[ bq ~ xr com.sun.rsasign.p��(!g�� L at Ljava/lang/String;[ bt [Ljava/lang/String;xr com.sun.rsasign.c�"dyU�|  xpt Javaur [Ljava.lang.String;��V��{G  xp   q ~ ur [B���T�  xp   ��ccR}o���[!#I����lo������
    ����^"`8�|���Z>������&
    d ����"B��
    ^5���a����jw9�����D���D�)�*3/h��7�|��I�d�$�4f�8_�|���yuq ~
    How i can generated the key pairs in base 64 or binary????
    Thanxs for help me
    Luis Navarro Nu�ez
    Santiago.
    Chile.
    South America.

    I don't use ABA but BouncyCastle
    this could help you :
    try
    java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    java.security.KeyPairGenerator kg = java.security.KeyPairGenerator.getInstance("RSA","BC");
    java.security.KeyPair kp = kg.generateKeyPair();
    java.security.Key pub = kp.getPublic();
    java.security.Key pri = kp.getPrivate();
    System.out.println("pub: " + pub);
    System.out.println("pri: " + pri);
    byte[] pub_e = pub.getEncoded();
    byte[] pri_e = pri.getEncoded();
    java.io.PrintWriter o;
    java.io.DataInputStream i;
    java.io.File f;
    o = new java.io.PrintWriter(new java.io.FileOutputStream("d:/pub64"));
    o.println(new sun.misc.BASE64Encoder().encode(pub_e));
    o.close();
    o = new java.io.PrintWriter(new java.io.FileOutputStream("d:/pri64"));
    o.println(new sun.misc.BASE64Encoder().encode(pri_e));
    o.close();
    java.io.BufferedReader br = new java.io.BufferedReader(new java.io.FileReader("d:/pub64"));
    StringBuffer keyBase64 = new StringBuffer();
    String line = br.readLine ();
    while(line != null)
    keyBase64.append (line);
    line = br.readLine ();
    byte [] pubBytes = new sun.misc.BASE64Decoder().decodeBuffer(keyBase64.toString ());
    br = new java.io.BufferedReader(new java.io.FileReader("d:/pri64"));
    keyBase64 = new StringBuffer();
    line = br.readLine ();
    while(line != null)
    keyBase64.append (line);
    line = br.readLine ();
    byte [] priBytes = new sun.misc.BASE64Decoder().decodeBuffer(keyBase64.toString ());
    java.security.KeyFactory kf = java.security.KeyFactory.getInstance("RSA","BC");
    java.security.Key pubKey = kf.generatePublic(new java.security.spec.X509EncodedKeySpec(pubBytes));
    System.out.println("pub: " + pubKey);
    java.security.Key priKey = kf.generatePrivate(new java.security.spec.PKCS8EncodedKeySpec(priBytes));
    System.out.println("pri: " + priKey);
    catch(Exception e)
    e.printStackTrace ();
    }

  • Problems using NSS library as PKCS#11 provider with JAVA 6

    Hi,
    I�m trying to configure JAVA 6 on Solaris 10 SPARC to use Mozilla NSS library as PKCS#11 provider (to achieve FIPS-140 certification for my application). I�m following the guidelines from http://java.sun.com/javase/6/docs/technotes/guides/security/p11guide.html#NSS but unfortunately something doesn�t work for me as expected...
    Let me describe the exact steps that I followed (because devil may be in the small details :-)
    I downloaded NSS 3.11.4 and NSPR 4.6.4 binaries from mozilla.org (32 bit �debug� versions for Solaris 9, because these were the only �binary� versions for SPARC available on Mozilla site and as far as I understand these are the exact versions that passed FIPS-140 certification), unpacked them under the /opt directory and copied both of them into a single /opt/nss tree as follows:
    mkdir /opt/nss
    cp �r /opt/nss-3.11.4/* /opt/nss
    cp �r /opt/nspr-4.6.4/* /opt/nss
    I created a PKCS#11 configuration file /opt/nss/pkcs11.cfg as per JAVA 6 security guide:
    name = NSScrypto
    nssLibraryDirectory = /opt/nss/lib
    nssDbMode = noDb
    attributes = compatibility
    (I know that this configuration is not for FIPS mode � but I thought that I�d better start with a simple NSS configuration)
    Then I modified /usr/jdk/jdk1.6.0_03/jre/lib/security/java.security file and replaced 1st provider with:
    security.provider.1=sun.security.pkcs11.SunPKCS11 /opt/nss/pkcs11.cfg
    Now everything should be in place � so I created a small JAVA program and ran it:
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESedeKeySpec;
    import javax.crypto.SecretKey;
    import javax.crypto.Cipher;
    import java.security.*;
    public class Test
    public static void main(String[] args)
    try
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
    DESedeKeySpec keySpec = null;
    keySpec = new DESedeKeySpec(new String("laKuf1Tcc6sOhsdPf49=m4es").getBytes());
    System.out.println("keyFactory provider: " + keyFactory.getProvider().getName());
    SecretKey key = keyFactory.generateSecret(keySpec);
    Cipher decryptCipher = Cipher.getInstance("DESede");
    decryptCipher.init(Cipher.DECRYPT_MODE, key);
    System.out.println("decryptCipher provider: " + decryptCipher.getProvider().getName());
    catch (Exception ex)
    ex.printStackTrace();
    Unfortunately it produced the following output:
    EMS-Server42# java test
    keyFactory provider: SunPKCS11-NSScrypto
    decryptCipher provider: SunJCE
    And when I comment out SunJCE provider in java.security file I get the following exception:
    java.security.NoSuchAlgorithmException: Cannot find any provider supporting DESede
    at javax.crypto.Cipher.getInstance(DashoA13*..)
    at test.main(test.java:38)
    So it looks like something is wrong with my NSS configuration. Because AFAIK DESede (3DES) is supported by the NSS library, but for some reason JAVA doesn�t see this algorithm implemented in NSS PKCS#11 provider.
    Any suggestions on what am I doing wrong?
    Best regards,
    Alex

    Works for me:
    import java.security.Provider;
    import java.security.SecureRandom;
    import java.security.Security;
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESedeKeySpec;
    import javax.crypto.spec.IvParameterSpec;
    public class Test
      public static void main(String[] args)
        try
          String configFileName = "/nss/nss.cfg";
          Provider nss = new sun.security.pkcs11.SunPKCS11(configFileName);
          Security.addProvider(nss);
          SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede", nss);
          DESedeKeySpec keySpec = new DESedeKeySpec(new String("laKuf1Tcc6sOhsdPf49=m4es").getBytes("UTF-8"));
          System.out.println("keyFactory provider: " + keyFactory.getProvider().getName());
          SecretKey key = keyFactory.generateSecret(keySpec);
          //iv for CBC mode - note, in practice you don't generate a random iv for decryption :)
          byte[] iv = new byte[8];  //64-bit block size for 3DES
          SecureRandom sr = SecureRandom.getInstance("PKCS11", nss);
          sr.nextBytes(iv);
          IvParameterSpec params = new IvParameterSpec(iv);
          Cipher decryptCipher = Cipher.getInstance("DESede/CBC/NoPadding", nss);
          decryptCipher.init(Cipher.DECRYPT_MODE, key, params);
          System.out.println("decryptCipher provider: " + decryptCipher.getProvider().getName());
        catch (Exception ex)
          ex.printStackTrace();
    }Oh, I wouldn't expect your key loading to work when you switch over to FIPS mode.
    cfg file:
    name = NSScrypto
    nssLibraryDirectory = /nss
    nssSecmodDirectory = /nss
    nssModule = fipsYields the following error:
    java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: Could not create key
    because you can't directly handle keying material in FIPS. You'll have to save the secret key in the NSS certDB or generate a random one each time and send it wrapped to the other side.

  • Sun PKCS#11 provider is caching PIN in applets

    I am coding an applet which uses Sun PKCS#11 provider to encrypt data. But There I am getting a strange problem of PIN caching.
    My Scenario_
    1. User login: User enters correct pin and Password is encrypted and sent to server.
    2. After log off button click, Login screen is displayed again. Now user enters wrong PIN.
    3. STRANGE Behavior: The encryption works well with the wrong key.
    1. I have removed the provider and readded it again.
    2. Created KeyStore again,
    But all this results in same problem.

    The program is just to simulate the issue. I understand that user have to pass the pin. In our GUI we have our own dialog to get the pin from user and pass it to the PKCS#11 provider that uses the pin while loading the keystore.
    cac.load(null, pin); // the pin passed in load method is not used at all
    My problem here is even after the proper pin is supplied by the user the active client PIN dialog is prompted. Whereas in LInux JRE this works fine.
    We have a command line application where active client dialog popup is not acceptable. We need to get the PIN from user as command argument and load the keystore.
    Please let me know if this clarifies the confusion.
    Thanks,
    Ruhul

  • Can a link 5 usb key paired with hp's wireless elite keyboard?

    Hi, I have a link 5 wireless mouse and a old hp's wireless elite keyboard.  I don't know if they both use bluetooth or one is bluetootha and the other 2.4GHz or not.  But can a link 5 usb key paired with a hp's version 1 wireless keyboard?  If not, how can I get a wireless usb key for my hp wireless eilte keyboard?

    Hello,
    A Link 5 USB mouse can be used with some devices and HP has listed them at the following link:
    HP Link-5technology liberates USB ports
    HP also introduced new PCaccessories with HP’s exclusive Link-5 technology. Link-5 allows users to connect up to fiveHP-compatible PC accessories with one receiver, freeing up valuableUSB ports.
    There are no drivers orsoftware to install. Users simply press the ”Connect” button on aLink-5 device to pair it with their PC. The wireless receiver then“remembers” all paired devices, making Link-5 accessories ideal forthose using a PC in multiple settings such as the home, office orother mobile locations.
    Link-5 delivers reliableconnectivity using 2.4-GHz wireless technology and has anintelligent sleep mode to ensure the longest possible battery life.The latest Link-5 accessories lineup includes:
    HP Wireless Mini Keyboard: Just the right mobile companion fora tablet or entertainment PC, this full-featured keyboard islightweight and ultra-small in size.
    HP Wireless Ultrathin Wireless Keyboard: Offering a stylishlook and feel, this keyboard is durable, full-featured and a greatvalue.
    HP Wireless Elite v2 Keyboard: Featuring a sleek, ultra-slimdesign, this keyboard offers superb performance and comfort.
    HP Wireless Optical Comfort Mouse: Offering a comfortable,secure grip for use in the right or left hand, this mouse featuresan optical sensor with adjustable sensitivity that works on mostsurfaces.
    HP Wireless Laser Comfort Mouse: Using a laser sensor withadjustable sensitivity, this mouse delivers optimal performance andworks on most surfaces.
    HP Wireless Mobile Mouse: Designed for users who are on the go,this mouse delivers reliable wireless connectivity at a greatvalue.
    It is only mention v2 not v1, so not sure if it will work. You should not be able to buy a key, because each device is sold with their specific usb receiver, so the answer is, you cannot get one, except if you buy  a new part.
    Thanks,
    I work for HP! Please remember to provide and if this helped click ON

  • SSL: How to use the same key pair for ABAP & JAVA?

    Hello,
    I want to setup an XI (3.0 on Netweaver04)installation in the way, that ABAP AS and JAVA AS use the same key pair for SSL. My problem is to define the same private key on ABAP and JAVA. With the JAVA Administrator I am able to define or import a private key. But I could not find a possibility in ABAP to manage private keys in order to use the same on as in JAVA. What is the procedure for this?
    Thanks and Regards,
    Frank Tottleben

    Hello,
    I want to setup an XI (3.0 on Netweaver04)installation in the way, that ABAP AS and JAVA AS use the same key pair for SSL. My problem is to define the same private key on ABAP and JAVA. With the JAVA Administrator I am able to define or import a private key. But I could not find a possibility in ABAP to manage private keys in order to use the same on as in JAVA. What is the procedure for this?
    Thanks and Regards,
    Frank Tottleben

  • Is a Public/Private Key Pair possible in SAP?

    I have a web service that I would like to run as part of a nightly script. I currently use username/password authentication, but it is not acceptable to have them hard coded, due to Sarbanes-Oxley rules. SAP's site claims to support authentication with x.509 certificates, but is unclear on the implementation details. How could I go about setting up and using a public/private key pair in SAP?

    Not really a portal question, and maybe you'll get a better result in a security forum...
    However, briefly, yes, the AS Java supports X509 certificates as an authentication mechansm. You need to use Visual Admin to generate a server side certificate, then you need the client side to register its own X509 certificate and then in the Java user admin you need to associate the client certificate with a known user. Now when the client executes the web service call it can pass the certificate and the AS Java will back translate the certificate to a real username.

  • How to retrieve public/ private from iKey token using Sun PKCS#11 provider

    Dear all,
    I'm trying to access one rainbow iKey 2032 token in Java 1.5 (Windows Environment) using Sun PKCS#11 provider. Token is stored with certificate. There is no problem to logging into the token using java.
         Provider p = new sun.security.pkcs11.SunPKCS11(configName);
         Security.addProvider(p);
         KeyStore ks = null;
         try{
              char[] pin = {'P','A','S','S','W','O','R','D'};
              ks = KeyStore.getInstance("pkcs11");
              ks.load(null,pin);
    catch(Exception e) {}
    Now I am wondering how to retrieve a public and private from token, so that I can encrypt and decrypt a plain text file. Could anyone give me a sample program for this?
    Your help is very much appreciated!!

    Hi Fred13
    1. I have the same pkcs.cfg and get the following trace. Can you help me understand? Does this imply a bad dkck201.dll? I would really like to get this working for my implementation. tia.
    lException in thread "main" java.security.ProviderException: Initialization failed
         at sun.security.pkcs11.SunPKCS11.<init>(SunPKCS11.java:175)
         at sun.security.pkcs11.SunPKCS11.<init>(SunPKCS11.java:76)
         at com.mkp.jce.chap1.ProviderDetail.main(ProviderDetail.java:38)
    Caused by: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_TOKEN_NOT_RECOGNIZED
         at sun.security.pkcs11.wrapper.PKCS11.C_GetTokenInfo(Native Method)
         at sun.security.pkcs11.Token.<init>(Token.java:105)
         at sun.security.pkcs11.SunPKCS11.initToken(SunPKCS11.java:555)
         at sun.security.pkcs11.SunPKCS11.<init>(SunPKCS11.java:169)
    2. (If I can be so indulgent of your time) Can you provide more information on cbp? I have done a search and there is little on it. It appears to be a new authentication framework tied in with sasl unique to 1.5. Any links for self education would be appreciated.

  • Sun PKCS#11 provider ignores the PIN while loading keystore in Windows JRE

    We are using smart card based login in our GUI application. We use active client for Card reader. We are using sun PKCS#11 provider to read certificate from the CARD. In the code we are passing PIN while loading the keystore. It seems the pin is getting ignored and we get active client pin dialog.
    PS: In linux JRE the pin passed while loading keystore is working properly.
    Below is the code snippet that i used for testing.
    public static void  main(String arg[]) throws Exception
           try
             //Create our certificates from our CAC Card
            String configName = "card.config";
             Provider p = new sun.security.pkcs11.SunPKCS11(configName);
             Security.addProvider(p);
             char[] pin = { '1', '2', '3', '4', '5', '6' };
             KeyStore cac = null;
             cac = KeyStore.getInstance("PKCS11");
             cac.load(null, pin);
             showInfoAboutCAC(cac);
          catch(Exception ex)
             ex.printStackTrace();
             System.exit(0);
       public static void showInfoAboutCAC(KeyStore ks) throws KeyStoreException, CertificateException, FileNotFoundException, IOException
          Enumeration<String> aliases = ks.aliases();
           int count = 0;
          while (aliases.hasMoreElements()) 
             String alias = aliases.nextElement();
             X509Certificate[] cchain = (X509Certificate[]) ks.getCertificateChain(alias);
             if (cchain != null){
             System.out.println("Certificate Chain for : " + alias);
             for (int i = 0; i < cchain.length; i ++)
                System.out.println(i + " SubjectDN: " + cchain.getSubjectDN());
    System.out.println(i + " IssuerDN: " + cchain[i].getIssuerDN());
    content of card.config is
    name = myConfig
    library = C:\\WINDOWS\\system32\\acpkcs211.dll
    Alternative we can see the same behaviour if we run the following command
    keytool -keystore NONE -storetype PKCS11 -providerClass sun.security.pkcs11.SunPKCS11 -providerArg "E:\work1\card.config" -list
    This command will ask ping in the command line and again active client PIN diaolog will be prompted.
    Please let me know if this a bug in Sun PKCS#11 provider in Windows and is there any work around to fix the issue.
    Enviornmnet Details::
    OS Win XP sp3
    Java version "1.6.0_17"
    Active client library version :
    P11 Library:
    Name:  acpkcs211.dll
    Version: 4-0-0-12
    Thanks in advanced
    Ruhul                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    The program is just to simulate the issue. I understand that user have to pass the pin. In our GUI we have our own dialog to get the pin from user and pass it to the PKCS#11 provider that uses the pin while loading the keystore.
    cac.load(null, pin); // the pin passed in load method is not used at all
    My problem here is even after the proper pin is supplied by the user the active client PIN dialog is prompted. Whereas in LInux JRE this works fine.
    We have a command line application where active client dialog popup is not acceptable. We need to get the PIN from user as command argument and load the keystore.
    Please let me know if this clarifies the confusion.
    Thanks,
    Ruhul

Maybe you are looking for

  • GLOBAL HINTS

    Hi Oracle Experts This is regarding GLOBAL HINTS I have a situation where all my views are defined in the views schema say "my_view". And all my fact tables are created in another schema say "my_fact". They are all in the same database. so schema1 =

  • Oaf requirement:have to display the order number but save the order id

    this is a standard practice with d2k forms.i have a requirement where in i have to store the order id in the table but have to display the user with the corresponding order numbr at all times..can any1 please help me with this***urgent***

  • Java import general question

    Hello All: I sometimes find packages on the net, but I dont know how to get them into my system, how do I download them? are they already included in J2SE 1.4 ?? forexample, I found this class that does checksum16, but when I declare a variable of th

  • Record only part of my desktop

    I use Quicktime Pro to record my screen and then create a Quicktime Movie. It always records all of my screen, but I really only want to record a portion of my desktop (say a specific app window). Can I do this?

  • Can't find the captured screen file on my Desktop, Please help!

    I'm using OS X 10.5.6 for a while but the problem just occurred recently (it worked fine before) I don't know why. I update the system often. I used the ShiftControl+Command3 or 4 shortcut but it doesn't work, I heard the shutter sound but the file d