Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Storing Certificate on Smart Card

843811Jun 13 2009 — edited Jun 17 2009
Hello guyz!

I have a little problem, so I hope you can help me.

I have a little task to do:
1. Enter smart card in a reader, a when the Token Login form arrives - log in to card and then start a main app. That's ok, it's working.
2. After that, select Generate Certificate Signing Request option. New form opens, user fills the data (dname data) and then a csr file is generated. That's ok, it's working.
3. Then, admin enter new smart card into reader and logs in to WebCA and processes that csr file, and get's .cer file if everything is fine. That's ok, it's working.
4. When user gets the .cer file. he has to import it on a smart card. When I try to do that with Card Reader official application everything is working, but I have to do it in my application.
There are two types of exceptions that gets on my nerve... Here's the code:
try {
            String provider = "SunPKCS11-SmartCard";
            KeyStore keyStore = KeyStore.getInstance("PKCS11", provider);
            keyStore.load(null, password);

            PrivateKey privateKey = null;

            Enumeration en = keyStore.aliases();
            String alias = null;
            while(en.hasMoreElements())
            {
                alias = (String)en.nextElement();
                JOptionPane.showMessageDialog(null, alias, "Crypto Trust Center", JOptionPane.ERROR_MESSAGE);
                privateKey = (PrivateKey)keyStore.getKey(alias, password);
            }

            if (readyForStoring)
            {
                FileInputStream fis = new FileInputStream(jTextFieldPlaceCERPath.getText().toString());
                BufferedInputStream bis = new BufferedInputStream(fis);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509Certificate cert = (X509Certificate)cf.generateCertificate(bis);
                X509Certificate[] chain = new X509Certificate[1];
                chain[0] = cert;

                if (keyStore.containsAlias(alias))
                {
                    keyStore.setKeyEntry(alias, privateKey, password, chain);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } 
The thing is, that when I put
CertificateFactory cf = CertificateFactory.getInstance("X.509");
exception is: invalid DER-encoded certificate. Then I tried to use BouncyCastle:
CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
and the exception is: key must Private or Secret.

After that, I tried to list aliases, because I thought that it's wrong, and guess what, on my card I physically have RSA Public Key 1024bits and RSA Private Key 1024bits, but they don't have alias at all??

What should I do???

This is my code for generating CSR file and for generating KeyPair:
String provider = "SunPKCS11-SmartCard";
String signatureAlgorithm   = "SHA1withRSA";

String name                 = jTextFieldFirstName.getText() + " " + jTextFieldLastName.getText();
String organization         = jTextFieldOrganization.getText();
String organizationalUnit   = jTextFieldOrganizationalUnit.getText();
String location             = jTextFieldPlace.getText();
String state                = jTextFieldState.getText();
String countryCode          = jTextFieldCountryCode.getText();
String email                = jTextFieldEmail.getText();

			KeyPairGenerator kpg = null;
			try
			{
				kpg = KeyPairGenerator.getInstance("RSA", provider);
			}
			catch (Exception e)
			{
				JOptionPane.showMessageDialog(null, e.toString(), "Crypto Trust Center", JOptionPane.ERROR_MESSAGE);
			}

			kpg.initialize(1024);

			KeyPair keyPair = kpg.generateKeyPair();

            String dname = String.format("CN = %s, O = %s, OU = %s,L = %s,S = %s,C = %s, EMAILADDRESS =%s", name, organization, organizationalUnit, location, state, countryCode, email);
			X500Principal subjectName = new X500Principal(dname);
			PKCS10CertificationRequest request = null;

			try
			{
				request = new PKCS10CertificationRequest(signatureAlgorithm, subjectName, keyPair.getPublic(), null, keyPair.getPrivate(), provider);
			}
			catch (Exception e)
			{
				JOptionPane.showMessageDialog(null, e.toString(), "Crypto Trust Center", JOptionPane.ERROR_MESSAGE);
			}

			byte [] encoded = request.getEncoded();
            

            String filename = jTextFieldPlaceFilePath.getText() + "\\" + name + ".csr";

            File csrFile = new File(filename);
            try {
                csrFile.createNewFile();
                csrFile.setWritable(true);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "Error creating file.", "Crypto Trust Center", JOptionPane.ERROR_MESSAGE);
            }

            BufferedOutputStream bos;
            try {
                bos = new BufferedOutputStream(new FileOutputStream(filename));
                bos.write( "-----BEGIN CERTIFICATE REQUEST-----\n".getBytes());
                bos.write(Base64.encode(encoded));
                bos.write( "-----END CERTIFICATE REQUEST-----".getBytes());
                bos.close();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "Error finding file.", "Crypto Trust Center", JOptionPane.ERROR_MESSAGE);
            }
So, my questions are:

1. If I'm using BouncyCastle provider, I suppose that the problem is in alias, because it doesn't exists!? at all.
2. If I'm using regular CertificateFactory, hmmm... in code, when I say
Base64.encode(encoded)
, encoded is "DER encoded", and when I say Base64 and add BEGIN CERTIFICATE REQUEST and END, I'm trying to create PEM-encoded CSR, and not DER-encoded (because exception is invalid DER-encoded certificate), so I tried to convert it. Is it a "good way" of converting DER encoded to PEM encoded?

Help in advance!!!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 15 2009
Added on Jun 13 2009
21 comments
1,095 views