protected void performLoad ( final CallbackHandler callbackHandler ) throws Exception { this.list.clear (); setLocked ( true ); this.keyStore.load ( new KeyStore.LoadStoreParameter () { @Override public ProtectionParameter getProtectionParameter () { return new KeyStore.CallbackHandlerProtection ( new CallbackHandlerTranslator ( callbackHandler ) ); } } ); setLocked ( false ); extractKeys ( null ); }
/** * Asymmetric cryptography - only the private key from generated pair is used. * Pre-condition: #certificateAlias refers to existing certificate * * @throws {@link NullPointerException} when #certificateAlias is @code{null} */ public void addPrivateKey(String keyAlias, String certificateAlias, String password) { keyAlias = String.format("%s (%s)", keyAlias, certificateAlias); try { Certificate[] certChain = keystore.getCertificateChain(certificateAlias); if (certChain == null) { LoggerFactory.getLogger(getClass()).warn("Could not find certificate"); certChain = new Certificate[0]; } Entry entry = new PrivateKeyEntry(generateKeyPair().getPrivate(), certChain); ProtectionParameter protParam = new KeyStore.PasswordProtection(password.toCharArray()); keystore.setEntry(keyAlias, entry, protParam); } catch (KeyStoreException | NoSuchAlgorithmException ex) { throw new RuntimeException("Unable to add new private key", ex); } }
/** {@inheritDoc} */ @Override public KeyStore.Entry engineGetEntry(final String alias, final ProtectionParameter protParam) { if (protParam instanceof KeyStore.PasswordProtection) { final PasswordCallback pwc = new CachePasswordCallback(((KeyStore.PasswordProtection)protParam).getPassword()); this.cryptoCard.setPasswordCallback(pwc); } if (!engineContainsAlias(alias)) { return null; } final PrivateKey key = (PrivateKey) engineGetKey( alias, null // Le pasamos null porque ya hemos establecido el PasswordCallback o el CallbackHander antes ); return new PrivateKeyEntry(key, engineGetCertificateChain(alias)); }
@Override protected final KeyStore.ProtectionParameter getKeyProtection( final String entryAlias, final X509Certificate entryCert, final KeyEntryPasswordProvider entryPasswordProvider) { if (null == entryPasswordProvider) { return null; } return new KeyStore.CallbackHandlerProtection(new CallbackHandler() { @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { PasswordCallback c = (PasswordCallback) callbacks[0]; c.setPassword(entryPasswordProvider.getPassword(entryAlias, entryCert)); } }); }
/** * @param keyStoreType the type of the keystore (jks, pkcs12, etc) * @param keyStorePath the file-system path of the keystore * @param certificateSelector the selector of signing certificate * @param keyStorePasswordProvider the provider of the keystore loading password * @param entryPasswordProvider the provider of entry passwords * @param returnFullChain indicates of the full certificate chain should be returned, if available * @throws KeyStoreException */ public FileSystemKeyStoreKeyingDataProvider( final String keyStoreType, final String keyStorePath, SigningCertSelector certificateSelector, KeyStorePasswordProvider keyStorePasswordProvider, KeyEntryPasswordProvider entryPasswordProvider, boolean returnFullChain) throws KeyStoreException { super(new KeyStoreBuilderCreator() { @Override public Builder getBuilder(ProtectionParameter loadProtection) { return KeyStore.Builder.newInstance( keyStoreType, null, new File(keyStorePath), loadProtection); } }, certificateSelector, keyStorePasswordProvider, entryPasswordProvider, returnFullChain); }
@Override public Entry engineGetEntry(String alias, ProtectionParameter protParam) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { LOGGER.debug("engineGetEntry: {}", alias); if ("Authentication".equals(alias) || "Signature".equals(alias)) { PrivateKey privateKey = (PrivateKey) engineGetKey(alias, null); Certificate[] chain = engineGetCertificateChain(alias); PrivateKeyEntry privateKeyEntry = new PrivateKeyEntry(privateKey, chain); return privateKeyEntry; } if ("CA".equals(alias) || "Root".equals(alias) || "RRN".equals(alias)) { Certificate certificate = engineGetCertificate(alias); TrustedCertificateEntry trustedCertificateEntry = new TrustedCertificateEntry(certificate); return trustedCertificateEntry; } return super.engineGetEntry(alias, protParam); }
@Override public void engineLoad(LoadStoreParameter param) throws IOException, NoSuchAlgorithmException, CertificateException { if (param == null) { engineLoad(null, null); return; } ProtectionParameter pParam = param.getProtectionParameter(); if (pParam == null) { throw new NoSuchAlgorithmException(); } if (pParam instanceof PasswordProtection) { char[] password = ((PasswordProtection) pParam).getPassword(); if (password == null) { throw new NoSuchAlgorithmException(); } else { return; } } throw new CertificateException(); }
@Override public void engineStore(LoadStoreParameter param) throws IOException, NoSuchAlgorithmException, CertificateException { if (param == null) { throw new IOException(); } ProtectionParameter pParam = param.getProtectionParameter(); if (pParam instanceof PasswordProtection) { char[] password = ((PasswordProtection) pParam).getPassword(); if (password == null) { throw new NoSuchAlgorithmException(); } else if (password.length == 0) { throw new CertificateException(); } return; } throw new UnsupportedOperationException(); }
public void test_getKeyStore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException { String alias = "BKS"; char[] pwd = new char[] { '1', '2', '3', '4', '5', '6' }; InputStream fis = KeyStore2Test.class .getResourceAsStream("builderimpl.ks"); KeyStore ks = KeyStore.getInstance(alias); ks.load(fis, pwd); Builder b = Builder.newInstance(ks, new PasswordProtection(pwd)); KeyStore firstKeyStore = b.getKeyStore(); ProtectionParameter firstProtParameter = b .getProtectionParameter(alias); assertSame(firstKeyStore, b.getKeyStore()); assertSame(firstProtParameter, b.getProtectionParameter(alias)); b = Builder.newInstance(alias, ks.getProvider(), new KeyStore.PasswordProtection(pwd)); firstKeyStore = b.getKeyStore(); firstProtParameter = b.getProtectionParameter(alias); assertNotSame(firstKeyStore, b.getKeyStore()); assertSame(firstProtParameter, b.getProtectionParameter(alias)); }
/** {@inheritDoc} */ @Override public void engineLoad(final KeyStore.LoadStoreParameter param) throws IOException { if (param != null) { final ProtectionParameter pp = param.getProtectionParameter(); if (pp instanceof KeyStore.CallbackHandlerProtection) { if (((KeyStore.CallbackHandlerProtection) pp).getCallbackHandler() == null) { throw new IllegalArgumentException("El CallbackHandler no puede ser nulo"); //$NON-NLS-1$ } this.cryptoCard = new Ceres( CeresProvider.getDefaultApduConnection(), new JseCryptoHelper() ); this.cryptoCard.setCallbackHandler(((KeyStore.CallbackHandlerProtection) pp).getCallbackHandler()); } else if (pp instanceof KeyStore.PasswordProtection) { final PasswordCallback pwc = new CeresPasswordCallback((PasswordProtection) pp); this.cryptoCard = new Ceres( CeresProvider.getDefaultApduConnection(), new JseCryptoHelper() ); this.cryptoCard.setPasswordCallback(pwc); } else { Logger.getLogger("es.gob.jmulticard").warning( //$NON-NLS-1$ "Se ha proporcionado un LoadStoreParameter de tipo no soportado, se ignorara: " + (pp != null ? pp.getClass().getName() : "NULO") //$NON-NLS-1$ //$NON-NLS-2$ ); } } else { this.cryptoCard = new Ceres( CeresProvider.getDefaultApduConnection(), new JseCryptoHelper() ); } userCertAliases = Arrays.asList(this.cryptoCard.getAliases()); }
/** {@inheritDoc} */ @Override public KeyStore.Entry engineGetEntry(final String alias, final ProtectionParameter protParam) { if(protParam instanceof KeyStore.CallbackHandlerProtection) { // Establecemos el CallbackHandler final CallbackHandler chp = ((KeyStore.CallbackHandlerProtection) protParam).getCallbackHandler(); if(chp != null) { this.cryptoCard.setCallbackHandler(chp); } } else if (protParam instanceof KeyStore.PasswordProtection) { // Establecemos el PasswordCallback final PasswordCallback pwc = new CachePasswordCallback(((KeyStore.PasswordProtection)protParam).getPassword()); this.cryptoCard.setPasswordCallback(pwc); } else { LOGGER.warning( "Se ha proporcionado un ProtectionParameter de tipo no soportado, se ignorara: " + (protParam != null ? protParam.getClass().getName() : "NULO") //$NON-NLS-1$ //$NON-NLS-2$ ); } if (!engineContainsAlias(alias)) { return null; } final PrivateKey key = (PrivateKey) engineGetKey( alias, null // Le pasamos null porque ya hemos establecido el PasswordCallback o el CallbackHander antes ); return new PrivateKeyEntry(key, engineGetCertificateChain(alias)); }
public static KeyStore createAndLoadDynamicKeystore(RSAPrivateKey rsaPrivateKey, Certificate certificate) throws KeyManagementException { logger.debug("Generating Keystore from RSA private key and X509 certificate"); Certificate[] certificateChain = { certificate }; PrivateKeyEntry privateKeyEntry = new KeyStore.PrivateKeyEntry(rsaPrivateKey, certificateChain); ProtectionParameter protectionParameter = new KeyStore.PasswordProtection(KEY_PASSWORD); KeyStore keystore = null; try { keystore = KeyStore.getInstance(KEYSTORE_INSTANCE_TYPE); keystore.load(null, null); keystore.setEntry(KEYSTORE_ALIAS, privateKeyEntry, protectionParameter); } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException ex) { throw new KeyManagementException(ex); } return keystore; }
/** * Creates an instance of this class using {@code wrappingAlgorithm} which will encrypt data to * the keys specified by {@code aliasNames}. */ public KeyStoreProvider(final KeyStore keystore, final ProtectionParameter protection, final String providerName, final String wrappingAlgorithm, final String... aliasNames) { keystore_ = keystore; protection_ = protection; wrappingAlgorithm_ = wrappingAlgorithm; aliasNames_ = Arrays.asList(aliasNames); providerName_ = providerName; keyAlgorithm_ = wrappingAlgorithm.split("/", 2)[0].toUpperCase(); }
/** * The provider name is used as a key to search for installed providers. If a * provider exists with the same name, it will be used even if it relies on a * different native library. * @param nativeLibraryPath the path for the native library of the specific PKCS#11 provider * @param providerName this string is concatenated with the prefix SunPKCS11- to produce this provider instance's name * @param slotId the id of the slot that this provider instance is to be associated with (can be {@code null}) * @param certificateSelector the selector of signing certificate * @param keyStorePasswordProvider the provider of the keystore loading password (can be {@code null}) * @param entryPasswordProvider the provider of entry passwords (may be {@code null}) * @param returnFullChain indicates of the full certificate chain should be returned, if available * @throws KeyStoreException */ public PKCS11KeyStoreKeyingDataProvider( final String nativeLibraryPath, final String providerName, final Integer slotId, SigningCertSelector certificateSelector, KeyStorePasswordProvider keyStorePasswordProvider, KeyEntryPasswordProvider entryPasswordProvider, boolean returnFullChain) throws KeyStoreException { super(new KeyStoreBuilderCreator() { @Override public Builder getBuilder(ProtectionParameter loadProtection) { Provider p = getInstalledProvider(providerName); if (p == null) { StringBuilder config = new StringBuilder("name = ").append(providerName); config.append(System.getProperty("line.separator")); config.append("library = ").append(nativeLibraryPath); if(slotId != null) { config.append(System.getProperty("line.separator")); config.append("slot = ").append(slotId); } ByteArrayInputStream configStream = new ByteArrayInputStream(config.toString().getBytes()); p = createPkcs11Provider(configStream); Security.addProvider(p); } return KeyStore.Builder.newInstance("PKCS11", p, loadProtection); } }, certificateSelector, keyStorePasswordProvider, entryPasswordProvider, returnFullChain); }
@Override protected KeyStore.ProtectionParameter getKeyProtection( String entryAlias, X509Certificate entryCert, KeyEntryPasswordProvider entryPasswordProvider) { return new KeyStore.PasswordProtection(entryPasswordProvider.getPassword(entryAlias, entryCert)); }
@Override @SuppressWarnings("restriction") KeyStore getKeyStore() throws DSSException { if (_keyStore == null) { try { _keyStore = KeyStore.getInstance("PKCS11", getProvider()); _keyStore.load(new KeyStore.LoadStoreParameter() { @Override public ProtectionParameter getProtectionParameter() { return new KeyStore.CallbackHandlerProtection(new CallbackHandler() { @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback c : callbacks) { if (c instanceof PasswordCallback) { ((PasswordCallback) c).setPassword(callback.getPassword()); return; } } throw new RuntimeException("No password callback"); } }); } }); } catch (Exception e) { if (e instanceof sun.security.pkcs11.wrapper.PKCS11Exception) { if ("CKR_PIN_INCORRECT".equals(e.getMessage())) { throw new DSSException("Bad password for PKCS11", e); } } throw new DSSException("Can't initialize Sun PKCS#11 security provider. Reason: " + e.getMessage(), e); } } return _keyStore; }
private KSPrivateKeyEntry getKSPrivateKeyEntry(final String alias, ProtectionParameter passwordProtection) { KeyStore keyStore = getKeyStore(); try { if (keyStore.isKeyEntry(alias)) { final PrivateKeyEntry entry = (PrivateKeyEntry) keyStore.getEntry(alias, passwordProtection); return new KSPrivateKeyEntry(alias, entry); } } catch (GeneralSecurityException e) { throw new DSSException("Unable to retrieve key for alias '" + alias + "'", e); } return null; }
private static void createKeystore(String keystore, String storepass, String alias, String dname) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, CommandTypeValidationException, IOException, InvalidKeyException, SignatureException { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); File keystoreFile = new File(keystore); FileOutputStream outStream = new FileOutputStream(keystoreFile); // loading the keystore from a null stream creates a new instance ks.load( null, storepass.toCharArray() ); KeyPairGenerator dsaKeyPairGenerator = KeyPairGenerator.getInstance("RSA"); dsaKeyPairGenerator.initialize(1024); KeyPair keyPair = dsaKeyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); Signature certificateSignature = Signature.getInstance("MD5withRSA"); SignedObject so = new SignedObject(publicKey, privateKey, certificateSignature); Certificate publicCertificate = null; Certificate[] publicCertificateChain = new Certificate[]{}; CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); KeyStore.Entry privateKeyEntry = new KeyStore.PrivateKeyEntry(privateKey, publicCertificateChain); ProtectionParameter protection = new KeyStore.PasswordProtection(storepass.toCharArray()); ks.setEntry(alias, privateKeyEntry, protection); //ks.setKeyEntry(getAlias(), key, chain); ks.store( outStream, storepass.toCharArray() ); }
public KeyStoreMaterialsProvider(KeyStore keyStore, String encryptionAlias, String signingAlias, ProtectionParameter encryptionProtection, ProtectionParameter signingProtection, Map<String, String> description) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { super(); this.keyStore = keyStore; this.encryptionAlias = encryptionAlias; this.signingAlias = signingAlias; this.encryptionProtection = encryptionProtection; this.signingProtection = signingProtection; this.description = Collections.unmodifiableMap(new HashMap<String, String>(description)); validateKeys(); loadKeys(); }
public static void newPrivateKey(KeyStore keystore, TypedCertificate certificate) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException { String path = typeToPath(certificate.getType()) + certificate.getCert().getSubjectX500Principal().getName(); PrivateKeyEntry keyEntry = new PrivateKeyEntry(certificate.getPrivateKey(), getCertificateChain( keystore, certificate).certsToArray()); if (!keystore.containsAlias(path)) { ProtectionParameter pp = new PasswordProtection(PRIVATE_KEY_PASSWORD.toCharArray()); keystore.setEntry(path, keyEntry, pp); } }
public static void newEntity(KeyStore keystore, TypedCertificate certificate) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException { PrivateKeyEntry keyEntry = new PrivateKeyEntry(certificate.getPrivateKey(), getCertificateChain( keystore, certificate).certsToArray()); if (keystore.containsAlias(KEYSTORE_ENTITY_KEY_PATH)) { keystore.deleteEntry(KEYSTORE_ENTITY_KEY_PATH); } ProtectionParameter pp = new PasswordProtection(PRIVATE_KEY_PASSWORD.toCharArray()); keystore.setEntry(KEYSTORE_ENTITY_KEY_PATH, keyEntry, pp); }
public static void newApplicationPrivateKey(KeyStore keystore, TypedCertificate certificate) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException { PrivateKeyEntry keyEntry = new PrivateKeyEntry(certificate.getPrivateKey(), getCertificateChain( keystore, certificate).certsToArray()); if (keystore.containsAlias(KEYSTORE_ENTITY_KEY_PATH)) { keystore.deleteEntry(KEYSTORE_ENTITY_KEY_PATH); } ProtectionParameter pp = new PasswordProtection(PRIVATE_KEY_PASSWORD.toCharArray()); keystore.setEntry(KEYSTORE_APPLICATION_KEY_PATH, keyEntry, pp); }
public ProtectionParameter getProtectionParameter() { return protectionParameter; }
public void setProtectionParameter(ProtectionParameter protectionParameter) { this.protectionParameter = protectionParameter; }
public PKCS12StoreParameter(OutputStream out, ProtectionParameter protectionParameter) { this(out, protectionParameter, false); }
public PKCS12StoreParameter(OutputStream out, ProtectionParameter protectionParameter, boolean forDEREncoding) { this.out = out; this.protectionParameter = protectionParameter; this.forDEREncoding = forDEREncoding; }
private ProtectionParameter createProtection(final EntryDescriptor descr) { return new PasswordProtection(descr.getPassword().toCharArray()); }
public KeyStoreBuilder withKeyStoreProtection(ProtectionParameter keyStoreProtection) { this.keyStoreProtection = requireNonNull(keyStoreProtection, "'keyStoreProtection' must not be null."); return this; }
/** {@inheritDoc} */ @Override public void engineLoad(final KeyStore.LoadStoreParameter param) throws IOException { if (param != null) { final ProtectionParameter pp = param.getProtectionParameter(); if (pp instanceof KeyStore.CallbackHandlerProtection) { if (((KeyStore.CallbackHandlerProtection) pp).getCallbackHandler() == null) { throw new IllegalArgumentException("El CallbackHandler no puede ser nulo"); //$NON-NLS-1$ } this.cryptoCard = DnieFactory.getDnie( DnieProvider.getDefaultApduConnection(), null, new JseCryptoHelper(), ((KeyStore.CallbackHandlerProtection) pp).getCallbackHandler() ); } else if (pp instanceof KeyStore.PasswordProtection) { final PasswordCallback pwc = new DniePasswordCallback((PasswordProtection) pp); this.cryptoCard = DnieFactory.getDnie( DnieProvider.getDefaultApduConnection(), pwc, new JseCryptoHelper(), null ); } else { LOGGER.warning( "Se ha proporcionado un LoadStoreParameter de tipo no soportado, se ignorara: " + (pp != null ? pp.getClass().getName() : "NULO") //$NON-NLS-1$ //$NON-NLS-2$ ); } } else { this.cryptoCard = DnieFactory.getDnie( DnieProvider.getDefaultApduConnection(), null, new JseCryptoHelper(), null ); } this.aliases = Arrays.asList(this.cryptoCard.getAliases()); }
/** * Creates an instance of this class using {@code wrappingAlgorithm} which will work * <em>for decrypt only</em>. */ public KeyStoreProvider(final KeyStore keystore, final ProtectionParameter protection, final String providerName, final String wrappingAlgorithm) { this(keystore, protection, providerName, wrappingAlgorithm, new String[0]); }
public PKCS12StoreParameter(OutputStream out, ProtectionParameter protectionParameter) { super(out, protectionParameter, false); }
public PKCS12StoreParameter(OutputStream out, ProtectionParameter protectionParameter, boolean forDEREncoding) { super(out, protectionParameter, forDEREncoding); }
public void engineStore(LoadStoreParameter param) throws IOException, NoSuchAlgorithmException, CertificateException { if (param == null) { throw new IllegalArgumentException("'param' arg cannot be null"); } if (!(param instanceof PKCS12StoreParameter || param instanceof JDKPKCS12StoreParameter)) { throw new IllegalArgumentException( "No support for 'param' of type " + param.getClass().getName()); } PKCS12StoreParameter bcParam; if (param instanceof PKCS12StoreParameter) { bcParam = (PKCS12StoreParameter)param; } else { bcParam = new PKCS12StoreParameter(((JDKPKCS12StoreParameter)param).getOutputStream(), param.getProtectionParameter(), ((JDKPKCS12StoreParameter)param).isUseDEREncoding()); } char[] password; ProtectionParameter protParam = param.getProtectionParameter(); if (protParam == null) { password = null; } else if (protParam instanceof KeyStore.PasswordProtection) { password = ((KeyStore.PasswordProtection)protParam).getPassword(); } else { throw new IllegalArgumentException( "No support for protection parameter of type " + protParam.getClass().getName()); } doStore(bcParam.getOutputStream(), password, bcParam.isForDEREncoding()); }