static KeyStore getKeyStore() throws Exception { InputStream in = new FileInputStream(new File(BASE, "rsakeys.ks")); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(in, password); in.close(); return ks; }
private static KeyStore readKeyStore(String name) throws Exception { File file = new File(PATH, name); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(in, passwd); in.close(); return ks; }
public static HttpClient getCertifiedHttpClient() throws IDPTokenManagerException { HttpClient client = null; InputStream inStream = null; try { if (Constants.SERVER_PROTOCOL.equalsIgnoreCase("https://")) { KeyStore localTrustStore = KeyStore.getInstance("BKS"); inStream = IdentityProxy.getInstance() .getContext() .getResources() .openRawResource(R.raw.emm_truststore); localTrustStore.load(inStream, Constants.TRUSTSTORE_PASSWORD.toCharArray()); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), Constants.HTTP)); SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); schemeRegistry.register(new Scheme("https", sslSocketFactory, Constants.HTTPS)); HttpParams params = new BasicHttpParams(); ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry); client = new DefaultHttpClient(connectionManager, params); } else { client = new DefaultHttpClient(); } } catch (KeyStoreException e) { String errorMsg = "Error occurred while accessing keystore."; Log.e(TAG, errorMsg); throw new IDPTokenManagerException(errorMsg, e); } catch (CertificateException e) { String errorMsg = "Error occurred while loading certificate."; Log.e(TAG, errorMsg); throw new IDPTokenManagerException(errorMsg, e); } catch (NoSuchAlgorithmException e) { String errorMsg = "Error occurred while due to mismatch of defined algorithm."; Log.e(TAG, errorMsg); throw new IDPTokenManagerException(errorMsg, e); } catch (UnrecoverableKeyException e) { String errorMsg = "Error occurred while accessing keystore."; Log.e(TAG, errorMsg); throw new IDPTokenManagerException(errorMsg, e); } catch (KeyManagementException e) { String errorMsg = "Error occurred while accessing keystore."; Log.e(TAG, errorMsg); throw new IDPTokenManagerException(errorMsg, e); } catch (IOException e) { String errorMsg = "Error occurred while loading trust store. "; Log.e(TAG, errorMsg); throw new IDPTokenManagerException(errorMsg, e); } finally { StreamHandlerUtil.closeInputStream(inStream, TAG); } return client; }
public void testDefaults() throws Exception { Properties p = initProps(); KeyStore ks = KeyStoreUtil.createKeyStore(p); List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases())); assertIsomorphic(SetUtil.set("mykey", "mycert"), SetUtil.theSet(aliases)); assertNotNull(ks.getCertificate("mycert")); assertNull(ks.getCertificate("foocert")); assertEquals("JCEKS", ks.getType()); }
void assertPubKs(File file, String pass, List<String> hosts) throws Exception { KeyStore ks = loadKeyStore("jceks", file, pass); List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases())); assertEquals(hosts.size(), aliases.size()); for (String host : hosts) { String alias = host + ".crt"; Certificate cert = ks.getCertificate(alias); assertNotNull(cert); assertEquals("X.509", cert.getType()); } }
/** * Method decrypts the data with the RSA private key corresponding to this certificate (which was * used to encrypt it). Decryption will be done with keystore * * @param data data to be decrypted. * @param token index of authentication token * @param pin PIN code * @return decrypted data. * @throws DigiDocException for all decryption errors */ public byte[] decrypt(byte[] data, int token, String pin) throws DigiDocException { try { if (m_keyStore == null) throw new DigiDocException( DigiDocException.ERR_NOT_INITED, "Keystore not initialized", null); String alias = getTokenName(token); if (alias == null) throw new DigiDocException( DigiDocException.ERR_TOKEN_LOGIN, "Invalid token nr: " + token, null); // get key if (m_logger.isDebugEnabled()) m_logger.debug( "loading key: " + alias + " passwd-len: " + ((pin != null) ? pin.length() : 0)); Key key = m_keyStore.getKey(alias, pin.toCharArray()); if (m_logger.isDebugEnabled()) m_logger.debug("Key: " + ((key != null) ? "OK, algorithm: " + key.getAlgorithm() : "NULL")); if (key == null) throw new DigiDocException( DigiDocException.ERR_TOKEN_LOGIN, "Invalid password for token: " + alias, null); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, key); byte[] decdata = cipher.doFinal(data); if (m_logger.isDebugEnabled()) m_logger.debug("Decrypted len: " + ((decdata != null) ? decdata.length : 0)); return decdata; } catch (Exception ex) { m_logger.error("Error decrypting: " + ex); } return null; }
/** * Initialisation if a supplied key is defined in the properties. This supplied key must be in a * keystore which can be generated using the keystoreGenerator file in demos. The keystore must be * on the classpath to find it. * * @throws KeyStoreException * @throws Exception * @throws IOException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws UnrecoverableKeyException */ private void initConfiguredKey() throws Exception { InputStream inputStream = null; // must not use default keystore type - as does not support secret keys KeyStore store = KeyStore.getInstance("JCEKS"); SecretKey tempKey = null; try { // load in keystore using this thread's classloader inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(keyStoreName); if (inputStream == null) inputStream = new FileInputStream(keyStoreName); // we can't find a keystore here - if (inputStream == null) { throw new Exception( "Unable to load keystore " + keyStoreName + " ensure file is on classpath"); } // we have located a file lets load the keystore try { store.load(inputStream, storePassword.toCharArray()); // loaded keystore - get the key tempKey = (SecretKey) store.getKey(alias, keyPassword.toCharArray()); } catch (IOException e) { throw new Exception("Unable to load keystore " + keyStoreName + ": " + e); } catch (NoSuchAlgorithmException e) { throw new Exception("No Such algorithm " + keyStoreName + ": " + e); } catch (CertificateException e) { throw new Exception("Certificate exception " + keyStoreName + ": " + e); } if (tempKey == null) throw new Exception("Unable to retrieve key '" + alias + "' from keystore " + keyStoreName); // set the key here setSecretKey(tempKey); if (symAlgorithm.equals(DEFAULT_SYM_ALGO)) symAlgorithm = tempKey.getAlgorithm(); // set the fact we are using a supplied key suppliedKey = true; queue_down = queue_up = false; } finally { Util.close(inputStream); } }
public void testCreateSharedPLNKeyStores() throws Exception { List<String> hosts = ListUtil.list("host1", "host2.foo.bar", "host3"); List<String> hosts2 = ListUtil.list("host3", "host4"); File dir = getTempDir(); File pub = new File(dir, "pub.ks"); KeyStoreUtil.createSharedPLNKeyStores( dir, hosts, pub, "pubpass", MiscTestUtil.getSecureRandom()); assertPubKs(pub, "pubpass", hosts); for (String host : hosts) { assertPrivateKs( new File(dir, host + ".jceks"), StringUtil.fromFile(new File(dir, host + ".pass")), host); } KeyStore pubks1 = loadKeyStore("jceks", new File(dir, "pub.ks"), "pubpass"); Certificate host1cert1 = pubks1.getCertificate("host1.crt"); Certificate host3cert1 = pubks1.getCertificate("host3.crt"); String host1priv1 = StringUtil.fromFile(new File(dir, "host1.jceks")); String host3priv1 = StringUtil.fromFile(new File(dir, "host3.jceks")); // Now add host4 and generate a new key for host3 KeyStoreUtil.createSharedPLNKeyStores( dir, hosts2, pub, "pubpass", MiscTestUtil.getSecureRandom()); List<String> both = ListUtils.sum(hosts, hosts2); assertPubKs(pub, "pubpass", both); for (String host : both) { assertPrivateKs( new File(dir, host + ".jceks"), StringUtil.fromFile(new File(dir, host + ".pass")), host); } KeyStore pubks2 = loadKeyStore("jceks", new File(dir, "pub.ks"), "pubpass"); // host1 should have the same cert, host3 not Certificate host1cert2 = pubks2.getCertificate("host1.crt"); Certificate host3cert2 = pubks2.getCertificate("host3.crt"); assertEquals(host1cert1, host1cert2); assertNotEquals(host3cert1, host3cert2); // host1's private key file should be the same, host3's not String host1priv2 = StringUtil.fromFile(new File(dir, "host1.jceks")); String host3priv2 = StringUtil.fromFile(new File(dir, "host3.jceks")); assertEquals(host1priv1, host1priv2); assertNotEquals(host3priv1, host3priv2); }
/** * Returns the n-th token name or alias * * @param nIdx index of token * @return alias */ private String getTokenName(int nIdx) { try { if (m_keyStore != null) { Enumeration eAliases = m_keyStore.aliases(); for (int i = 0; eAliases.hasMoreElements(); i++) { String alias = (String) eAliases.nextElement(); if (i == nIdx) return alias; } } } catch (Exception ex) { m_logger.error("Error reading store aliases: " + ex); } return null; }
/** * Method returns a X.509 certificate object readed from the active token and representing an user * public key certificate value. * * @return X.509 certificate object. * @throws DigiDocException if getting X.509 public key certificate fails or the requested * certificate type X.509 is not available in the default provider package */ public X509Certificate getCertificate(int token, String pin) throws DigiDocException { if (m_keyStore == null) throw new DigiDocException(DigiDocException.ERR_NOT_INITED, "Keystore not initialized", null); String alias = getTokenName(token); if (alias == null) throw new DigiDocException( DigiDocException.ERR_TOKEN_LOGIN, "Invalid token nr: " + token, null); try { return (X509Certificate) m_keyStore.getCertificate(alias); } catch (Exception ex) { m_logger.error("Error reading cert for alias: " + alias + " - " + ex); } return null; }
public void main(Provider p) throws Exception { /* * Use Solaris SPARC 11.2 or later to avoid an intermittent failure * when running SunPKCS11-Solaris (8044554) */ if (p.getName().equals("SunPKCS11-Solaris") && System.getProperty("os.name").equals("SunOS") && System.getProperty("os.arch").equals("sparcv9") && System.getProperty("os.version").compareTo("5.11") <= 0 && getDistro().compareTo("11.2") < 0) { System.out.println( "SunPKCS11-Solaris provider requires " + "Solaris SPARC 11.2 or later, skipping"); return; } long start = System.currentTimeMillis(); provider = p; data = new byte[2048]; new Random().nextBytes(data); KeyStore ks = getKeyStore(); KeyFactory kf = KeyFactory.getInstance("RSA", provider); for (Enumeration e = ks.aliases(); e.hasMoreElements(); ) { String alias = (String) e.nextElement(); if (ks.isKeyEntry(alias)) { System.out.println("* Key " + alias + "..."); PrivateKey privateKey = (PrivateKey) ks.getKey(alias, password); PublicKey publicKey = ks.getCertificate(alias).getPublicKey(); privateKey = (PrivateKey) kf.translateKey(privateKey); publicKey = (PublicKey) kf.translateKey(publicKey); test(privateKey, publicKey); } } long stop = System.currentTimeMillis(); System.out.println("All tests passed (" + (stop - start) + " ms)."); }
public boolean load(String storeName, String storeType, String passwd) throws DigiDocException { FileInputStream fis = null; try { if (m_logger.isDebugEnabled()) m_logger.debug("Load store: " + storeName + " type: " + storeType); m_keyStore = KeyStore.getInstance(storeType); if (m_keyStore != null) { m_keyStore.load(fis = new FileInputStream(storeName), passwd.toCharArray()); return true; } } catch (Exception ex) { m_logger.error("Error loading store: " + storeName + " - " + ex); } finally { if (fis != null) { try { fis.close(); fis = null; } catch (Exception ex2) { m_logger.error("Error closing pkcs12: " + storeName + " - " + ex2); } } } return false; }
/** * Method returns an array of strings representing the list of available token names. * * @return an array of available token names. * @throws DigiDocException if reading the token information fails. */ public String[] getAvailableTokenNames() throws DigiDocException { Vector vec = new Vector(); try { if (m_keyStore != null) { Enumeration eAliases = m_keyStore.aliases(); while (eAliases.hasMoreElements()) { String alias = (String) eAliases.nextElement(); vec.add(alias); } } } catch (Exception ex) { m_logger.error("Error reading store aliases: " + ex); } String[] arr = new String[vec.size()]; for (int i = 0; (vec != null) && (i < vec.size()); i++) arr[i] = (String) vec.elementAt(i); return arr; }
public void testStore() throws Exception { File dir = getTempDir(); File file = new File(dir, "test.ks"); Properties p = initProps(); p.put(KeyStoreUtil.PROP_KEYSTORE_FILE, file.toString()); assertFalse(file.exists()); KeyStore ks = KeyStoreUtil.createKeyStore(p); assertTrue(file.exists()); KeyStore ks2 = loadKeyStore(ks.getType(), file, PASSWD); List aliases = ListUtil.fromIterator(new EnumerationIterator(ks2.aliases())); assertIsomorphic(SetUtil.set("mykey", "mycert"), SetUtil.theSet(aliases)); assertNotNull(ks2.getCertificate("mycert")); assertNull(ks2.getCertificate("foocert")); assertEquals("JCEKS", ks2.getType()); }
void assertPrivateKs(File file, String pass, String alias) throws Exception { KeyStore ks = loadKeyStore("jceks", file, alias); List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases())); assertEquals(2, aliases.size()); Certificate cert = ks.getCertificate(alias + ".crt"); assertNotNull(cert); assertEquals("X.509", cert.getType()); assertTrue(ks.isKeyEntry(alias + ".key")); assertTrue(ks.isCertificateEntry(alias + ".crt")); Key key = ks.getKey(alias + ".key", pass.toCharArray()); assertNotNull(key); assertEquals("RSA", key.getAlgorithm()); }
/** * Method returns a digital signature. It finds the RSA private key object from the active token * and then signs the given data with this key and RSA mechanism. * * @param digest digest of the data to be signed. * @param token token index * @param passwd users pin code or in case of pkcs12 file password * @param sig Signature object to provide info about desired signature method * @return an array of bytes containing digital signature. * @throws DigiDocException if signing the data fails. */ public byte[] sign(byte[] xml, int token, String passwd, Signature sig) throws DigiDocException { try { if (m_keyStore == null) throw new DigiDocException( DigiDocException.ERR_NOT_INITED, "Keystore not initialized", null); String alias = getTokenName(token); if (alias == null) throw new DigiDocException( DigiDocException.ERR_TOKEN_LOGIN, "Invalid token nr: " + token, null); // get key if (m_logger.isDebugEnabled()) m_logger.debug( "loading key: " + alias + " passwd-len: " + ((passwd != null) ? passwd.length() : 0)); Key key = m_keyStore.getKey(alias, passwd.toCharArray()); if (m_logger.isDebugEnabled()) m_logger.debug("Key: " + ((key != null) ? "OK, algorithm: " + key.getAlgorithm() : "NULL")); if (key == null) throw new DigiDocException( DigiDocException.ERR_TOKEN_LOGIN, "Invalid password for token nr: " + token, null); String sigMeth = null; if (sig != null && sig.getSignedInfo() != null && sig.getSignedInfo().getSignatureMethod() != null) sigMeth = sig.getSignedInfo().getSignatureMethod(); if (m_logger.isDebugEnabled()) m_logger.debug("Signing\n---\n" + new String(xml) + "\n---\n method: " + sigMeth); java.security.Signature instance = sigMeth2SigSignatureInstance(sig, key); if (m_logger.isDebugEnabled()) m_logger.debug("Signature instance: " + ((instance != null) ? "OK" : "NULL")); instance.initSign((PrivateKey) key); instance.update(xml); byte[] signature = instance.sign(); boolean bEcCvcKey = isCvcEcKey(sig); if (m_logger.isDebugEnabled()) m_logger.debug( "Signature algorithm: " + key.getAlgorithm() + " siglen: " + signature.length + " ec-key: " + bEcCvcKey); if (bEcCvcKey) { int nKeyLen = ((ECPrivateKey) key).getParams().getCurve().getField().getFieldSize(); int nReqLen = ((int) Math.ceil((double) nKeyLen / 8)) * 2; int nSigLen = signature.length; if (m_logger.isDebugEnabled()) m_logger.debug("EC Signature length: " + nSigLen + " required: " + nReqLen); if (nSigLen < nReqLen) { if (m_logger.isDebugEnabled()) m_logger.debug("Padding EC signature length: " + nSigLen + " to required: " + nReqLen); byte[] padsig = new byte[nReqLen]; System.arraycopy(signature, 0, padsig, (nReqLen - nSigLen) / 2, nSigLen / 2); System.arraycopy( signature, nSigLen / 2, padsig, (nReqLen / 2) + (nReqLen - nSigLen) / 2, nSigLen / 2); signature = padsig; } } if (m_logger.isDebugEnabled() && signature != null) m_logger.debug( "Signature len: " + signature.length + "\n---\n sig: " + ConvertUtils.bin2hex(signature)); return signature; } catch (DigiDocException ex) { m_logger.error("DigiDoc Error signing: " + ex); throw ex; } catch (Exception ex) { m_logger.error("Error signing: " + ex); } return null; }
KeyStore loadKeyStore(String type, File file, String passwd) throws Exception { KeyStore ks = KeyStore.getInstance(type); FileInputStream fis = new FileInputStream(file); ks.load(fis, passwd.toCharArray()); return ks; }
public void signJar(Jar jar) { if (digestNames == null || digestNames.length == 0) error("Need at least one digest algorithm name, none are specified"); if (keystoreFile == null || !keystoreFile.getAbsoluteFile().exists()) { error("No such keystore file: " + keystoreFile); return; } if (alias == null) { error("Private key alias not set for signing"); return; } MessageDigest digestAlgorithms[] = new MessageDigest[digestNames.length]; getAlgorithms(digestNames, digestAlgorithms); try { Manifest manifest = jar.getManifest(); manifest.getMainAttributes().putValue("Signed-By", "Bnd"); // Create a new manifest that contains the // Name parts with the specified digests ByteArrayOutputStream o = new ByteArrayOutputStream(); manifest.write(o); doManifest(jar, digestNames, digestAlgorithms, o); o.flush(); byte newManifestBytes[] = o.toByteArray(); jar.putResource("META-INF/MANIFEST.MF", new EmbeddedResource(newManifestBytes, 0)); // Use the bytes from the new manifest to create // a signature file byte[] signatureFileBytes = doSignatureFile(digestNames, digestAlgorithms, newManifestBytes); jar.putResource("META-INF/BND.SF", new EmbeddedResource(signatureFileBytes, 0)); // Now we must create an RSA signature // this requires the private key from the keystore KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); KeyStore.PrivateKeyEntry privateKeyEntry = null; java.io.FileInputStream keystoreInputStream = null; try { keystoreInputStream = new java.io.FileInputStream(keystoreFile); char[] pw = password == null ? new char[0] : password.toCharArray(); keystore.load(keystoreInputStream, pw); keystoreInputStream.close(); privateKeyEntry = (PrivateKeyEntry) keystore.getEntry(alias, new KeyStore.PasswordProtection(pw)); } catch (Exception e) { error( "No able to load the private key from the give keystore(" + keystoreFile.getAbsolutePath() + ") with alias " + alias + " : " + e); return; } finally { IO.close(keystoreInputStream); } PrivateKey privateKey = privateKeyEntry.getPrivateKey(); Signature signature = Signature.getInstance("MD5withRSA"); signature.initSign(privateKey); signature.update(signatureFileBytes); signature.sign(); // TODO, place the SF in a PCKS#7 structure ... // no standard class for this? The following // is an idea but we will to have do ASN.1 BER // encoding ... ByteArrayOutputStream tmpStream = new ByteArrayOutputStream(); jar.putResource("META-INF/BND.RSA", new EmbeddedResource(tmpStream.toByteArray(), 0)); } catch (Exception e) { error("During signing: " + e); } }
public static synchronized void setGlobalSSLAuth( String keypath, String keypassword, String trustpath, String trustpassword) { // load the stores if defined try { if (trustpath != null && trustpassword != null) { truststore = KeyStore.getInstance(KeyStore.getDefaultType()); try (FileInputStream instream = new FileInputStream(new File(trustpath))) { truststore.load(instream, trustpassword.toCharArray()); } } else truststore = null; if (keypath != null && keypassword != null) { keystore = KeyStore.getInstance(KeyStore.getDefaultType()); try (FileInputStream instream = new FileInputStream(new File(keypath))) { keystore.load(instream, keypassword.toCharArray()); } } else keystore = null; } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException ex) { log.error("Illegal -D keystore parameters: " + ex.getMessage()); truststore = null; keystore = null; } try { // set up the context SSLContext scxt = null; if (IGNORECERTS) { scxt = SSLContext.getInstance("TLS"); TrustManager[] trust_mgr = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String t) {} public void checkServerTrusted(X509Certificate[] certs, String t) {} } }; scxt.init( null, // key manager trust_mgr, // trust manager new SecureRandom()); // random number generator } else { SSLContextBuilder sslbuilder = SSLContexts.custom(); TrustStrategy strat = new LooseTrustStrategy(); if (truststore != null) sslbuilder.loadTrustMaterial(truststore, strat); else sslbuilder.loadTrustMaterial(strat); sslbuilder.loadTrustMaterial(truststore, new LooseTrustStrategy()); if (keystore != null) sslbuilder.loadKeyMaterial(keystore, keypassword.toCharArray()); scxt = sslbuilder.build(); } globalsslfactory = new SSLConnectionSocketFactory(scxt, new NoopHostnameVerifier()); RegistryBuilder rb = RegistryBuilder.<ConnectionSocketFactory>create(); rb.register("https", globalsslfactory); sslregistry = rb.build(); } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException | UnrecoverableEntryException e) { log.error("Failed to set key/trust store(s): " + e.getMessage()); sslregistry = null; globalsslfactory = null; } }