java.security.KeyStore.PrivateKeyEntry Java Examples

The following examples show how to use java.security.KeyStore.PrivateKeyEntry. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EncryptionUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public DataSealer initOldSealing() throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, IntegrationModuleException {

        // 0. BouncyCastle must be added as a security provider
        // because the ehealth.etee.crypto library depends on it.
        Security.addProvider(new BouncyCastleProvider());

        // 1.0. Get the DataSealerFactory
//        DataSealerFactory dataSealerFactory = DataSealerFactory.getInstance();
        // 1.1. Get the sender's private authentication key for signature
        // creation
        PrivateKeyEntry keyAndCerts = KeyManager.getKeyAndCertificates(getOldKeyStore(), AUTHENTICATION_ALIAS, DEFAULT_PASSWORD);
        PrivateKey clientAuthenticationKey = keyAndCerts.getPrivateKey();

        // 1.2. Get the sender's authentication certificate that matches the
        // authentication key
        X509Certificate clientAuthCertificate = getOldCertificate();
        LOG.debug("Encryption initialized for :" + clientAuthCertificate.getSubjectDN());

        // 1.3 Get the DataSealer for client
        final SigningCredential signingCredential = SigningCredential.create(clientAuthenticationKey, clientAuthCertificate);
        DataSealer dataSealer = DataSealerBuilder.newBuilder().addOCSPPolicy(OCSPPolicy.NONE).addSigningPolicy(SigningPolicy.EHEALTH_CERT, signingCredential).addPublicKeyPolicy(EncryptionPolicy.KNOWN_RECIPIENT)
                .addSecretKeyPolicy(EncryptionPolicy.UNKNOWN_RECIPIENT).build();
        return dataSealer;
    }
 
Example #2
Source File: EncryptionUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public DataSealer initOldSealing() throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, IntegrationModuleException {

        // 0. BouncyCastle must be added as a security provider
        // because the ehealth.etee.crypto library depends on it.
        Security.addProvider(new BouncyCastleProvider());

        // 1.0. Get the DataSealerFactory
//        DataSealerFactory dataSealerFactory = DataSealerFactory.getInstance();
        // 1.1. Get the sender's private authentication key for signature
        // creation
        PrivateKeyEntry keyAndCerts = KeyManager.getKeyAndCertificates(getOldKeyStore(), AUTHENTICATION_ALIAS, DEFAULT_PASSWORD);
        PrivateKey clientAuthenticationKey = keyAndCerts.getPrivateKey();

        // 1.2. Get the sender's authentication certificate that matches the
        // authentication key
        X509Certificate clientAuthCertificate = getOldCertificate();
        LOG.debug("Encryption initialized for :" + clientAuthCertificate.getSubjectDN());

        // 1.3 Get the DataSealer for client
        final SigningCredential signingCredential = SigningCredential.create(clientAuthenticationKey, clientAuthCertificate);
        DataSealer dataSealer = DataSealerBuilder.newBuilder().addOCSPPolicy(OCSPPolicy.NONE).addSigningPolicy(SigningPolicy.EHEALTH_CERT, signingCredential).addPublicKeyPolicy(EncryptionPolicy.KNOWN_RECIPIENT)
                .addSecretKeyPolicy(EncryptionPolicy.UNKNOWN_RECIPIENT).build();
        return dataSealer;
    }
 
Example #3
Source File: PatchBuilder.java    From atlas with Apache License 2.0 6 votes vote down vote up
public PatchBuilder(File outFile, File dexFile, PrivateKeyEntry key,
                    PrintStream verboseStream) {
    try {
        if (null != key) {
            mBuilder = new SignedJarBuilder(
                    new FileOutputStream(outFile, false), key.getPrivateKey(),
                    (X509Certificate) key.getCertificate());
        } else {
            mBuilder = new SignedJarBuilder(
                    new FileOutputStream(outFile, false), null,
                    null);
        }
        mBuilder.writeFile(dexFile, "classes.dex");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #4
Source File: AbstractKeyStoreTokenConnection.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private DSSPrivateKeyEntry getDSSPrivateKeyEntry(KeyStore keyStore, String alias, PasswordProtection passwordProtection) {
	try {
		if (keyStore.isKeyEntry(alias)) {
			final Entry entry = keyStore.getEntry(alias, passwordProtection);
			if (entry instanceof PrivateKeyEntry) {
				PrivateKeyEntry pke = (PrivateKeyEntry) entry;
				return new KSPrivateKeyEntry(alias, pke);
			} else {
				LOG.warn("Skipped entry (unsupported class : {})", entry.getClass().getSimpleName());
			}
		} else {
			LOG.debug("No related/supported key found for alias '{}'", alias);
		}
	} catch (GeneralSecurityException e) {
		throw new DSSException("Unable to retrieve key from keystore", e);
	}
	return null;
}
 
Example #5
Source File: KeyStoreMaterialsProvider.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
private static KeyPair entry2Pair(Entry entry) {
    PublicKey pub = null;
    PrivateKey priv = null;

    if (entry instanceof PrivateKeyEntry) {
        PrivateKeyEntry pk = (PrivateKeyEntry) entry;
        if (pk.getCertificate() != null) {
            pub = pk.getCertificate().getPublicKey();
        }
        priv = pk.getPrivateKey();
    } else if (entry instanceof TrustedCertificateEntry) {
        TrustedCertificateEntry tc = (TrustedCertificateEntry) entry;
        pub = tc.getTrustedCertificate().getPublicKey();
    } else {
        throw new IllegalArgumentException(
                "Only entry types PrivateKeyEntry and TrustedCertificateEntry are supported.");
    }
    return new KeyPair(pub, priv);
}
 
Example #6
Source File: KeyStoreMaterialsProvider.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
private static KeyPair entry2Pair(Entry entry) {
    PublicKey pub = null;
    PrivateKey priv = null;

    if (entry instanceof PrivateKeyEntry) {
        PrivateKeyEntry pk = (PrivateKeyEntry) entry;
        if (pk.getCertificate() != null) {
            pub = pk.getCertificate().getPublicKey();
        }
        priv = pk.getPrivateKey();
    } else if (entry instanceof TrustedCertificateEntry) {
        TrustedCertificateEntry tc = (TrustedCertificateEntry) entry;
        pub = tc.getTrustedCertificate().getPublicKey();
    } else {
        throw new IllegalArgumentException(
                "Only entry types PrivateKeyEntry and TrustedCertificateEntry are supported.");
    }
    return new KeyPair(pub, priv);
}
 
Example #7
Source File: XmlSignature.java    From cstc with GNU General Public License v3.0 6 votes vote down vote up
protected KeyInfo getKeyInfo() throws Exception {
  PrivateKeyEntry keyEntry = this.selectedEntry;
  String keyInfoChoice = (String) includeKeyInfo.getSelectedItem();
  if( Boolean.parseBoolean(keyInfoChoice) ) {
    X509Certificate cert = (X509Certificate)keyEntry.getCertificate();
    KeyInfoFactory keyInfoFac = signatureFac.getKeyInfoFactory();
    List<Object> x509Content = new ArrayList<Object>();
    if( this.subject.isSelected() ) {
      x509Content.add(cert.getSubjectX500Principal().getName());
    } 
    if( this.serialIssuer.isSelected() ) {
      x509Content.add(keyInfoFac.newX509IssuerSerial(cert.getIssuerX500Principal().getName(),cert.getSerialNumber()));
    }
    if( this.issuer.isSelected() ) {
      x509Content.add(cert.getIssuerX500Principal().getName());
    }
    if( this.certificate.isSelected() ) {
      x509Content.add(cert);
    }
    X509Data xd = keyInfoFac.newX509Data(x509Content);
    return keyInfoFac.newKeyInfo(Collections.singletonList(xd));
  }
  return (KeyInfo)null;
}
 
Example #8
Source File: SoapMultiSignature.java    From cstc with GNU General Public License v3.0 6 votes vote down vote up
private KeyInfo getKeyInfo(XMLSignatureFactory fac, PrivateKeyEntry keyEntry) throws Exception {
  String keyInfoChoice = (String) includeKeyInfo.getSelectedItem();
  if( Boolean.parseBoolean(keyInfoChoice) ) {
    KeyInfo keyInfo;
    X509Certificate cert = (X509Certificate)keyEntry.getCertificate();
    KeyInfoFactory keyInfoFac = fac.getKeyInfoFactory();
    List<Object> x509Content = new ArrayList<Object>();
    if( this.subject.isSelected() ) {
      x509Content.add(cert.getSubjectX500Principal().getName());
    } 
    if( this.serialIssuer.isSelected() ) {
      x509Content.add(keyInfoFac.newX509IssuerSerial(cert.getIssuerX500Principal().getName(),cert.getSerialNumber()));
    }
    if( this.issuer.isSelected() ) {
      x509Content.add(cert.getIssuerX500Principal().getName());
    }
    if( this.certificate.isSelected() ) {
      x509Content.add(cert);
    }
    X509Data xd = keyInfoFac.newX509Data(x509Content);
    keyInfo = keyInfoFac.newKeyInfo(Collections.singletonList(xd));
    return keyInfo;
  }
  return (KeyInfo)null;
}
 
Example #9
Source File: KeyStoreMaterialsProviderTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {

    KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
    macGen.init(256, Utils.getRng());
    macKey = macGen.generateKey();

    KeyGenerator aesGen = KeyGenerator.getInstance("AES");
    aesGen.init(128, Utils.getRng());
    encryptionKey = aesGen.generateKey();

    keyStore = KeyStore.getInstance("jceks");
    keyStore.load(null, password.toCharArray());

    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec rsaSpec = new PKCS8EncodedKeySpec(Base64.decode(keyPem));
    privateKey = kf.generatePrivate(rsaSpec);
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    certificate = cf.generateCertificate(new ByteArrayInputStream(Base64.decode(certPem)));


    keyStore.setEntry("enc", new SecretKeyEntry(encryptionKey), passwordProtection);
    keyStore.setEntry("sig", new SecretKeyEntry(macKey), passwordProtection);
    keyStore.setEntry("enc-a", new PrivateKeyEntry(privateKey, new Certificate[]{certificate}), passwordProtection);
    keyStore.setEntry("sig-a", new PrivateKeyEntry(privateKey, new Certificate[]{certificate}), passwordProtection);
    keyStore.setCertificateEntry("trustedCert", certificate);
}
 
Example #10
Source File: KSPrivateKeyEntry.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * The default constructor for KSPrivateKeyEntry.
 * 
 * @param alias
 *            the given alias
 * @param privateKeyEntry
 *            the keystore private key entry
 */
public KSPrivateKeyEntry(final String alias, final PrivateKeyEntry privateKeyEntry) {
	this.alias = alias;
	certificate = new CertificateToken((X509Certificate) privateKeyEntry.getCertificate());
	final List<CertificateToken> x509CertificateList = new ArrayList<>();
	final Certificate[] simpleCertificateChain = privateKeyEntry.getCertificateChain();
	for (final Certificate currentCertificate : simpleCertificateChain) {
		x509CertificateList.add(new CertificateToken((X509Certificate) currentCertificate));
	}
	final CertificateToken[] certificateChain_ = new CertificateToken[x509CertificateList.size()];
	certificateChain = x509CertificateList.toArray(certificateChain_);
	privateKey = privateKeyEntry.getPrivateKey();
}
 
Example #11
Source File: KeyStoreMaterialsProviderTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
    
    KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
    macGen.init(256, Utils.getRng());
    macKey = macGen.generateKey();
    
    KeyGenerator aesGen = KeyGenerator.getInstance("AES");
    aesGen.init(128, Utils.getRng());
    encryptionKey = aesGen.generateKey();
    
    keyStore = KeyStore.getInstance("jceks");
    keyStore.load(null, password.toCharArray());
    
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec rsaSpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(keyPem));
    privateKey = kf.generatePrivate(rsaSpec);
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    certificate = cf.generateCertificate(new ByteArrayInputStream(Base64.getDecoder().decode(certPem)));
    
    
    keyStore.setEntry("enc", new SecretKeyEntry(encryptionKey), passwordProtection);
    keyStore.setEntry("sig", new SecretKeyEntry(macKey), passwordProtection);
    keyStore.setEntry("enc-a", new PrivateKeyEntry(privateKey, new Certificate[] {certificate}), passwordProtection);
    keyStore.setEntry("sig-a", new PrivateKeyEntry(privateKey, new Certificate[] {certificate}), passwordProtection);
    keyStore.setCertificateEntry("trustedCert", certificate);
}
 
Example #12
Source File: SoapMultiSignature.java    From cstc with GNU General Public License v3.0 5 votes vote down vote up
protected byte[] perform(byte[] input) throws Exception {

      String signMethod = (String)signatureMethod.getSelectedItem();
      PrivateKeyEntry keyEntry = this.selectedEntry;

      XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
      ArrayList<Reference> references = getReferences(fac);
      SignedInfo signatureInfo = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null), fac.newSignatureMethod(signatureMethods.get(signMethod), null), references);
      KeyInfo keyInfo = this.getKeyInfo(fac, keyEntry);
      XMLSignature signature = fac.newXMLSignature(signatureInfo, keyInfo);

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(input));
      try {
        validateIdAttributes(doc);
      } catch( Exception e ) {
        throw new IllegalArgumentException("Provided Id identifier seems to be invalid.");
      }
      DOMSignContext dsc = new DOMSignContext (keyEntry.getPrivateKey(), doc.getDocumentElement()); 
      signature.sign(dsc);

      DOMSource source = new DOMSource(doc);
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      StreamResult result = new StreamResult(bos);
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      transformer.transform(source, result);
      return bos.toByteArray();
	}
 
Example #13
Source File: CertificateHandler.java    From development with Apache License 2.0 5 votes vote down vote up
private void loadPrivateKeyEntry() throws GeneralSecurityException {
    rootPrivateKeyEntry = (PrivateKeyEntry) rootCaKeystore.getEntry(
            rootCaAlias,
            new PasswordProtection(rootCaPassword.toCharArray()));

    if (rootPrivateKeyEntry == null) {
        throw new RuntimeException(
                "Could not read private key entry from rootca keystore with alias "
                        + rootCaAlias);
    }
}
 
Example #14
Source File: SignTask.java    From development with Apache License 2.0 5 votes vote down vote up
private PrivateKeyEntry loadCAKeyEntry() throws IOException,
        GeneralSecurityException {
    final KeyStore keystore = loadKeyStore();
    final Entry entry = keystore.getEntry(this.alias,
            new PasswordProtection(this.password.toCharArray()));
    return (PrivateKeyEntry) entry;
}
 
Example #15
Source File: KeyStoreProvider.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
private JceMasterKey internalGetMasterKey(final String provider, final String keyId) {
    final Entry entry;
    try {
        entry = keystore_.getEntry(keyId, keystore_.isKeyEntry(keyId) ? protection_ : null);
    } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) {
        throw new UnsupportedProviderException(e);
    }
    if (entry == null) {
        throw new NoSuchMasterKeyException();
    }
    if (entry instanceof SecretKeyEntry) {
        final SecretKeyEntry skEntry = (SecretKeyEntry) entry;
        if (!skEntry.getSecretKey().getAlgorithm().equals(keyAlgorithm_)) {
            return null;
        }
        return JceMasterKey.getInstance(skEntry.getSecretKey(), provider, keyId, wrappingAlgorithm_);
    } else if (entry instanceof PrivateKeyEntry) {
        final PrivateKeyEntry pkEntry = (PrivateKeyEntry) entry;
        if (!pkEntry.getPrivateKey().getAlgorithm().equals(keyAlgorithm_)) {
            return null;
        }
        return JceMasterKey.getInstance(pkEntry.getCertificate().getPublicKey(), pkEntry.getPrivateKey(), provider,
                keyId, wrappingAlgorithm_);
    } else if (entry instanceof TrustedCertificateEntry) {
        final TrustedCertificateEntry certEntry = (TrustedCertificateEntry) entry;
        if (!certEntry.getTrustedCertificate().getPublicKey().getAlgorithm().equals(keyAlgorithm_)) {
            return null;
        }
        return JceMasterKey.getInstance(certEntry.getTrustedCertificate().getPublicKey(), null, provider, keyId,
                wrappingAlgorithm_);
    } else {
        throw new NoSuchMasterKeyException();
    }
}
 
Example #16
Source File: CloudSqlInstance.java    From cloud-sql-jdbc-socket-factory with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new SSLContext based on the provided parameters. This SSLContext will be used to
 * provide new SSLSockets that are authorized to connect to a Cloud SQL instance.
 */
private SSLContext createSslContext(
    KeyPair keyPair, Metadata metadata, Certificate ephemeralCertificate) {
  try {
    KeyStore authKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    authKeyStore.load(null, null);
    KeyStore.PrivateKeyEntry privateKey =
        new PrivateKeyEntry(keyPair.getPrivate(), new Certificate[] {ephemeralCertificate});
    authKeyStore.setEntry("ephemeral", privateKey, new PasswordProtection(new char[0]));
    KeyManagerFactory kmf =
        KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(authKeyStore, new char[0]);

    KeyStore trustedKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustedKeyStore.load(null, null);
    trustedKeyStore.setCertificateEntry("instance", metadata.getInstanceCaCertificate());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("X.509");
    tmf.init(trustedKeyStore);

    SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());

    return sslContext;
  } catch (GeneralSecurityException | IOException ex) {
    throw new RuntimeException(
        String.format(
            "[%s] Unable to create a SSLContext for the Cloud SQL instance.", connectionName),
        ex);
  }
}
 
Example #17
Source File: EncryptionUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the public key for authentication.
 *
 * @param keystore
 * @return the public key
 */
private PublicKey getPublicKey(KeyStore key, String privateKeyAlias, char[] privateKeyPassword) {

    try {
        PrivateKeyEntry keyAndCerts = KeyManager.getKeyAndCertificates(key, privateKeyAlias, privateKeyPassword);
        return keyAndCerts.getCertificate().getPublicKey();
    } catch (UnrecoverableKeyException e) {
        LOG.error("UnrecoverableKeyException", e);
        return null;
    }
}
 
Example #18
Source File: EncryptionUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the private key for authentication
 *
 * @param keystore
 * @return private key
 */
private PrivateKey getPrivateKey(KeyStore key, String privateKeyAlias, char[] privateKeyPassword) {

    try {
        PrivateKeyEntry keyAndCerts = KeyManager.getKeyAndCertificates(key, privateKeyAlias, privateKeyPassword);
        return keyAndCerts.getPrivateKey();
    } catch (UnrecoverableKeyException e) {
        LOG.error("UnrecoverableKeyException", e);
        return null;
    }
}
 
Example #19
Source File: EncryptionUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public void verifyDecryption(EncryptionToken myETK) throws IntegrationModuleException {
   boolean found = false;

   try {
      Enumeration aliases = this.getKeyStore().aliases();

      while(aliases.hasMoreElements()) {
         try {
            String alias = (String)aliases.nextElement();
            LOG.debug("verifyDecryption : " + alias);
            PrivateKeyEntry keyAndCerts = KeyManager.getKeyAndCertificates(this.getKeyStore(), alias, DEFAULT_PASSWORD);
            myETK.getCertificate().verify(keyAndCerts.getCertificate().getPublicKey());
            found = true;
         } catch (UnrecoverableKeyException var6) {
            ;
         } catch (NoSuchAlgorithmException var7) {
            ;
         } catch (InvalidKeyException var8) {
            ;
         } catch (CertificateException var9) {
            ;
         } catch (NoSuchProviderException var10) {
            ;
         } catch (SignatureException var11) {
            ;
         }
      }
   } catch (KeyStoreException var12) {
      ;
   }

   if (!found) {
      throw new IntegrationModuleException(I18nHelper.getLabel("error.etk.decryption.key"));
   }
}
 
Example #20
Source File: XmlSignature.java    From cstc with GNU General Public License v3.0 5 votes vote down vote up
protected void createSignature(Document document) throws Exception {
  String signMethod = (String)signatureMethod.getSelectedItem();
  PrivateKeyEntry keyEntry = this.selectedEntry;

  if( this.multiSignature )
    this.validateIdAttributes(document);
  ArrayList<Reference> references = this.getReferences();
  SignedInfo signatureInfo = signatureFac.newSignedInfo(signatureFac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null), signatureFac.newSignatureMethod(signatureMethods.get(signMethod), null), references);
  KeyInfo keyInfo = this.getKeyInfo();
  XMLSignature signature = signatureFac.newXMLSignature(signatureInfo, keyInfo);

  DOMSignContext dsc = new DOMSignContext (keyEntry.getPrivateKey(), document.getDocumentElement()); 
  signature.sign(dsc);
}
 
Example #21
Source File: EncryptionUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
     * Inits the sealing.
     *
     * @return the data sealer
     * @throws KeyStoreException          the key store exception
     * @throws UnrecoverableKeyException  the unrecoverable key exception
     * @throws NoSuchAlgorithmException   the no such algorithm exception
     * @throws CertificateException       the certificate exception
     * @throws IOException                Signals that an I/O exception has occurred.
     * @throws IntegrationModuleException
     * @throws IntegrationModuleException
     */
    public DataSealer initSealing() throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, CertificateException, IOException, IntegrationModuleException {

        // 0. BouncyCastle must be added as a security provider
        // because the ehealth.etee.crypto library depends on it.
        Security.addProvider(new BouncyCastleProvider());

        // 1.0. Get the DataSealerFactory
//        DataSealerFactory dataSealerFactory = DataSealerFactory.getInstance();
        // 1.1. Get the sender's private authentication key for signature
        // creation
        PrivateKeyEntry keyAndCerts = KeyManager.getKeyAndCertificates(getKeyStore(), AUTHENTICATION_ALIAS, DEFAULT_PASSWORD);
        PrivateKey clientAuthenticationKey = keyAndCerts.getPrivateKey();

        // 1.2. Get the sender's authentication certificate that matches the
        // authentication key
        X509Certificate clientAuthCertificate = getCertificate();
        LOG.debug("Encryption initialized for SubjectDN: " + clientAuthCertificate.getSubjectDN());
        LOG.debug("Encryption initialized for SerialNumber: " + clientAuthCertificate.getSerialNumber());
        LOG.debug("Encryption initialized for ThumbPrint: " + getThumbPrint(clientAuthCertificate));

        // 1.3 Get the DataSealer for client
        final SigningCredential signingCredential = SigningCredential.create(clientAuthenticationKey, clientAuthCertificate);
        DataSealer dataSealer = DataSealerBuilder.newBuilder().addOCSPPolicy(OCSPPolicy.NONE).addSigningPolicy(SigningPolicy.EHEALTH_CERT, signingCredential).addPublicKeyPolicy(EncryptionPolicy.KNOWN_RECIPIENT)
                .addSecretKeyPolicy(EncryptionPolicy.UNKNOWN_RECIPIENT).build();

        return dataSealer;
    }
 
Example #22
Source File: EncryptionUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the private key for authentication
 *
 * @param keystore
 * @return private key
 */
private PrivateKey getPrivateKey(KeyStore key, String privateKeyAlias, char[] privateKeyPassword) {

    try {
        PrivateKeyEntry keyAndCerts = KeyManager.getKeyAndCertificates(key, privateKeyAlias, privateKeyPassword);
        return keyAndCerts.getPrivateKey();
    } catch (UnrecoverableKeyException e) {
        LOG.error("UnrecoverableKeyException", e);
        return null;
    }
}
 
Example #23
Source File: EncryptionUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the public key for authentication.
 *
 * @param keystore
 * @return the public key
 */
private PublicKey getPublicKey(KeyStore key, String privateKeyAlias, char[] privateKeyPassword) {

    try {
        PrivateKeyEntry keyAndCerts = KeyManager.getKeyAndCertificates(key, privateKeyAlias, privateKeyPassword);
        return keyAndCerts.getCertificate().getPublicKey();
    } catch (UnrecoverableKeyException e) {
        LOG.error("UnrecoverableKeyException", e);
        return null;
    }
}
 
Example #24
Source File: EncryptionUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public DataSealer initSealing() throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, CertificateException, IOException, IntegrationModuleException {
   Security.addProvider(new BouncyCastleProvider());
   PrivateKeyEntry keyAndCerts = KeyManager.getKeyAndCertificates(this.getKeyStore(), "authentication", DEFAULT_PASSWORD);
   PrivateKey clientAuthenticationKey = keyAndCerts.getPrivateKey();
   X509Certificate clientAuthCertificate = this.getCertificate();
   LOG.debug("Encryption initialized for SubjectDN: " + clientAuthCertificate.getSubjectDN());
   LOG.debug("Encryption initialized for SerialNumber: " + clientAuthCertificate.getSerialNumber());
   LOG.debug("Encryption initialized for ThumbPrint: " + getThumbPrint(clientAuthCertificate));
   SigningCredential signingCredential = SigningCredential.create(clientAuthenticationKey, clientAuthCertificate);
   DataSealer dataSealer = DataSealerBuilder.newBuilder().addOCSPPolicy(OCSPPolicy.NONE).addSigningPolicy(SigningPolicy.EHEALTH_CERT, signingCredential).addPublicKeyPolicy(EncryptionPolicy.KNOWN_RECIPIENT).addSecretKeyPolicy(EncryptionPolicy.UNKNOWN_RECIPIENT).build();
   return dataSealer;
}
 
Example #25
Source File: EncryptionUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public DataSealer initOldSealing() throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, IntegrationModuleException {
   Security.addProvider(new BouncyCastleProvider());
   PrivateKeyEntry keyAndCerts = KeyManager.getKeyAndCertificates(this.getOldKeyStore(), "authentication", DEFAULT_PASSWORD);
   PrivateKey clientAuthenticationKey = keyAndCerts.getPrivateKey();
   X509Certificate clientAuthCertificate = this.getOldCertificate();
   LOG.debug("Encryption initialized for :" + clientAuthCertificate.getSubjectDN());
   SigningCredential signingCredential = SigningCredential.create(clientAuthenticationKey, clientAuthCertificate);
   DataSealer dataSealer = DataSealerBuilder.newBuilder().addOCSPPolicy(OCSPPolicy.NONE).addSigningPolicy(SigningPolicy.EHEALTH_CERT, signingCredential).addPublicKeyPolicy(EncryptionPolicy.KNOWN_RECIPIENT).addSecretKeyPolicy(EncryptionPolicy.UNKNOWN_RECIPIENT).build();
   return dataSealer;
}
 
Example #26
Source File: EncryptionUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private PrivateKey getPrivateKey(KeyStore key, String privateKeyAlias, char[] privateKeyPassword) {
   try {
      PrivateKeyEntry keyAndCerts = KeyManager.getKeyAndCertificates(key, privateKeyAlias, privateKeyPassword);
      return keyAndCerts.getPrivateKey();
   } catch (UnrecoverableKeyException var5) {
      LOG.error("UnrecoverableKeyException", var5);
      return null;
   }
}
 
Example #27
Source File: EncryptionUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private PublicKey getPublicKey(KeyStore key, String privateKeyAlias, char[] privateKeyPassword) {
   try {
      PrivateKeyEntry keyAndCerts = KeyManager.getKeyAndCertificates(key, privateKeyAlias, privateKeyPassword);
      return keyAndCerts.getCertificate().getPublicKey();
   } catch (UnrecoverableKeyException var5) {
      LOG.error("UnrecoverableKeyException", var5);
      return null;
   }
}
 
Example #28
Source File: EncryptionUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
     * Inits the sealing.
     *
     * @return the data sealer
     * @throws KeyStoreException          the key store exception
     * @throws UnrecoverableKeyException  the unrecoverable key exception
     * @throws NoSuchAlgorithmException   the no such algorithm exception
     * @throws CertificateException       the certificate exception
     * @throws IOException                Signals that an I/O exception has occurred.
     * @throws IntegrationModuleException
     * @throws IntegrationModuleException
     */
    public DataSealer initSealing() throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, CertificateException, IOException, IntegrationModuleException {

        // 0. BouncyCastle must be added as a security provider
        // because the ehealth.etee.crypto library depends on it.
        Security.addProvider(new BouncyCastleProvider());

        // 1.0. Get the DataSealerFactory
//        DataSealerFactory dataSealerFactory = DataSealerFactory.getInstance();
        // 1.1. Get the sender's private authentication key for signature
        // creation
        PrivateKeyEntry keyAndCerts = KeyManager.getKeyAndCertificates(getKeyStore(), AUTHENTICATION_ALIAS, DEFAULT_PASSWORD);
        PrivateKey clientAuthenticationKey = keyAndCerts.getPrivateKey();

        // 1.2. Get the sender's authentication certificate that matches the
        // authentication key
        X509Certificate clientAuthCertificate = getCertificate();
        LOG.debug("Encryption initialized for SubjectDN: " + clientAuthCertificate.getSubjectDN());
        LOG.debug("Encryption initialized for SerialNumber: " + clientAuthCertificate.getSerialNumber());
        LOG.debug("Encryption initialized for ThumbPrint: " + getThumbPrint(clientAuthCertificate));

        // 1.3 Get the DataSealer for client
        final SigningCredential signingCredential = SigningCredential.create(clientAuthenticationKey, clientAuthCertificate);
        DataSealer dataSealer = DataSealerBuilder.newBuilder().addOCSPPolicy(OCSPPolicy.NONE).addSigningPolicy(SigningPolicy.EHEALTH_CERT, signingCredential).addPublicKeyPolicy(EncryptionPolicy.KNOWN_RECIPIENT)
                .addSecretKeyPolicy(EncryptionPolicy.UNKNOWN_RECIPIENT).build();

        return dataSealer;
    }
 
Example #29
Source File: AddPrivateKey.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static void test(Provider p, PrivateKeyEntry entry) throws Exception {
    PrivateKey key = entry.getPrivateKey();
    X509Certificate[] chain = (X509Certificate[])entry.getCertificateChain();
    PublicKey publicKey = chain[0].getPublicKey();
    System.out.println(toString(key));
    sign(p, key, publicKey);

    KeyStore ks = KeyStore.getInstance("PKCS11", p);
    ks.load(null, null);
    if (ks.size() != 0) {
        throw new Exception("KeyStore not empty");
    }
    List<String> aliases;

    // test 1: add entry
    ks.setKeyEntry(ALIAS1, key, null, chain);
    aliases = aliases(ks);
    if (aliases.size() != 1) {
        throw new Exception("size not 1: " + aliases);
    }
    if (aliases.get(0).equals(ALIAS1) == false) {
        throw new Exception("alias mismatch: " + aliases);
    }

    PrivateKey key2 = (PrivateKey)ks.getKey(ALIAS1, null);
    System.out.println(toString(key2));
    X509Certificate[] chain2 =
            (X509Certificate[]) ks.getCertificateChain(ALIAS1);
    if (Arrays.equals(chain, chain2) == false) {
        throw new Exception("chain mismatch");
    }
    sign(p, key2, publicKey);

    ks.deleteEntry(ALIAS1);
    if (ks.size() != 0) {
        throw new Exception("KeyStore not empty");
    }

    // test 2: translate to session object, then add entry
    KeyFactory kf = KeyFactory.getInstance(key.getAlgorithm(), p);
    PrivateKey key3 = (PrivateKey)kf.translateKey(key);
    System.out.println(toString(key3));
    sign(p, key3, publicKey);

    ks.setKeyEntry(ALIAS2, key3, null, chain);
    aliases = aliases(ks);
    if (aliases.size() != 1) {
        throw new Exception("size not 1");
    }
    if (aliases.get(0).equals(ALIAS2) == false) {
        throw new Exception("alias mismatch: " + aliases);
    }

    PrivateKey key4 = (PrivateKey)ks.getKey(ALIAS2, null);
    System.out.println(toString(key4));
    X509Certificate[] chain4 = (X509Certificate[])
            ks.getCertificateChain(ALIAS2);
    if (Arrays.equals(chain, chain4) == false) {
        throw new Exception("chain mismatch");
    }
    sign(p, key4, publicKey);

    // test 3: change alias
    ks.setKeyEntry(ALIAS3, key3, null, chain);
    aliases = aliases(ks);
    if (aliases.size() != 1) {
        throw new Exception("size not 1");
    }
    if (aliases.get(0).equals(ALIAS3) == false) {
        throw new Exception("alias mismatch: " + aliases);
    }

    PrivateKey key5 = (PrivateKey)ks.getKey(ALIAS3, null);
    System.out.println(toString(key5));
    X509Certificate[] chain5 = (X509Certificate[])
            ks.getCertificateChain(ALIAS3);
    if (Arrays.equals(chain, chain5) == false) {
        throw new Exception("chain mismatch");
    }
    sign(p, key5, publicKey);

    ks.deleteEntry(ALIAS3);
    if (ks.size() != 0) {
        throw new Exception("KeyStore not empty");
    }

    System.out.println("OK");
}
 
Example #30
Source File: X509KeyManagerImpl.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
@Override
public PrivateKey getPrivateKey(String alias) {
    PrivateKeyEntry entry = getEntry(alias);
    return entry == null ? null : entry.getPrivateKey();
}