下面列出了java.security.KeyStore.PrivateKeyEntry#getPrivateKey ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
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;
}
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();
}
}
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);
}
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);
}
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();
}
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);
}
/**
* 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;
}
/**
* 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;
}
}
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;
}
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;
}
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;
}
}
/**
* 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;
}
/**
* 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;
}
}
/**
* 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();
}
@Override
public PrivateKey getPrivateKey(String alias) {
PrivateKeyEntry entry = getEntry(alias);
return entry == null ? null : entry.getPrivateKey();
}
@Override
public PrivateKey getPrivateKey(String alias) {
PrivateKeyEntry entry = getEntry(alias);
return entry == null ? null : entry.getPrivateKey();
}
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");
}
/**
* Signs and returns the w3c representation of the document containing the SAML assertion.
*
* @param document
* w3c document to be signed.
* @return w3c representation of the signed document.
* @throws TransformerException
* @throws NoSuchAlgorithmException
* @throws InvalidAlgorithmParameterException
* @throws KeyException
* @throws MarshalException
* @throws XMLSignatureException
*/
public Document signSamlAssertion(Document document) throws TransformerException, NoSuchAlgorithmException,
InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException {
if (document != null) {
PrivateKeyEntry entry = getPrivateKeyEntryFromKeystore();
PrivateKey privateKey = entry.getPrivateKey();
X509Certificate certificate = (X509Certificate) entry.getCertificate();
Element signedElement = signSamlAssertion(document, privateKey, certificate);
return signedElement.getOwnerDocument();
}
return null;
}