use of java.security.PrivateKey in project android_frameworks_base by ParanoidAndroid.
the class AndroidKeyStoreTest method testKeyStore_SetKeyEntry_Encrypted_Success.
public void testKeyStore_SetKeyEntry_Encrypted_Success() throws Exception {
setupPassword();
mKeyStore.load(null, null);
final CertificateFactory f = CertificateFactory.getInstance("X.509");
final Certificate caCert = f.generateCertificate(new ByteArrayInputStream(FAKE_CA_1));
KeyFactory keyFact = KeyFactory.getInstance("RSA");
PrivateKey privKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(FAKE_KEY_1));
final Certificate[] chain = new Certificate[2];
chain[0] = f.generateCertificate(new ByteArrayInputStream(FAKE_USER_1));
chain[1] = caCert;
mKeyStore.setKeyEntry(TEST_ALIAS_1, privKey, null, chain);
Entry actualEntry = mKeyStore.getEntry(TEST_ALIAS_1, null);
assertNotNull("Retrieved entry should exist", actualEntry);
assertTrue("Retrieved entry should be of type PrivateKeyEntry", actualEntry instanceof PrivateKeyEntry);
PrivateKeyEntry actual = (PrivateKeyEntry) actualEntry;
assertPrivateKeyEntryEquals(actual, FAKE_KEY_1, FAKE_USER_1, FAKE_CA_1);
}
use of java.security.PrivateKey in project OpenAttestation by OpenAttestation.
the class Pkcs12 method getRsaCredentialX509.
public RsaCredentialX509 getRsaCredentialX509(String keyAlias, String keyPassword) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException, FileNotFoundException, CertificateEncodingException {
// load the key pair
//NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException
KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keystore.getEntry(keyAlias, new KeyStore.PasswordProtection(keyPassword.toCharArray()));
if (pkEntry != null) {
PrivateKey myPrivateKey = pkEntry.getPrivateKey();
Certificate myCertificate = pkEntry.getCertificate();
if (myCertificate instanceof X509Certificate) {
//CertificateEncodingException, NoSuchAlgorithmException
return new RsaCredentialX509(myPrivateKey, (X509Certificate) myCertificate);
}
throw new IllegalArgumentException("Key has a certificate that is not X509: " + myCertificate.getType());
//PublicKey myPublicKey = pkEntry.getCertificate().getPublicKey();
//return new RsaCredential(myPrivateKey, myPublicKey);
}
// key pair not found
throw new FileNotFoundException("Keystore does not contain the specified key");
}
use of java.security.PrivateKey in project OpenAttestation by OpenAttestation.
the class Diagnostic method trySignature.
private static void trySignature() {
String algorithmName = "SHA1withRSA";
try {
// generate keypair
// NoSuchAlgorithmException, NoSuchProviderException
KeyPair keyPair = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
String plaintext = "This is the message being signed";
// generate signature
// NoSuchAlgorithmException, NoSuchProviderException
Signature instance = Signature.getInstance("SHA1withRSAEncryption", "BC");
// InvalidKeyException
instance.initSign(privateKey);
// SignatureException
instance.update((plaintext).getBytes());
byte[] signature = instance.sign();
System.out.println("Generated SHA1 with RSA signature of length: " + signature.length);
} catch (NoSuchProviderException e) {
System.err.println("Cannot use provider: BC: " + e.toString());
} catch (NoSuchAlgorithmException e) {
System.err.println("Cannot use algorithm: " + algorithmName + ": " + e.toString());
} catch (InvalidKeyException e) {
System.err.println("Cannot use key: " + e.toString());
} catch (SignatureException e) {
System.err.println("Cannot generate signature: " + e.toString());
}
}
use of java.security.PrivateKey in project Openfire by igniterealtime.
the class CertificateManager method installCert.
/**
* Imports a new signed certificate and its private key into the keystore. The certificate input
* stream may contain the signed certificate as well as its CA chain.
*
* @param keyStore key store where the certificate will be stored.
* @param trustStore key store where ca certificates are stored.
* @param keyPassword password of the keystore.
* @param alias the alias of the the new signed certificate.
* @param pkInputStream the stream containing the private key.
* @param passPhrase is the password phrased used when creating the private key.
* @param inputStream the stream containing the signed certificate.
* @return true if the certificate was successfully imported.
* @throws Exception if no certificates were found in the inputStream.
*/
public static boolean installCert(KeyStore keyStore, KeyStore trustStore, String keyPassword, String alias, InputStream pkInputStream, final String passPhrase, InputStream inputStream) throws Exception {
// Check that there is a certificate for the specified alias
X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
if (certificate != null) {
Log.warn("Certificate already exists for alias: " + alias);
return false;
}
PrivateKey privKey = parsePrivateKey(pkInputStream, passPhrase);
Collection<X509Certificate> certs = parseCertificates(inputStream);
if (certs.isEmpty()) {
throw new Exception("No certificates were found");
}
List<X509Certificate> newCerts;
if (certs.size() == 1) {
// Reply has only one certificate
newCerts = establishCertChain(keyStore, trustStore, certificate, certs.iterator().next());
} else {
// Reply has a chain of certificates
newCerts = validateReply(keyStore, trustStore, alias, certificate, certs);
}
if (newCerts == null) {
return false;
}
keyStore.setKeyEntry(alias, privKey, keyPassword.toCharArray(), newCerts.toArray(new X509Certificate[newCerts.size()]));
// Notify listeners that a new certificate has been created (and signed)
for (CertificateEventListener listener : listeners) {
try {
listener.certificateCreated(keyStore, alias, newCerts.get(0));
if (newCerts.size() > 1) {
listener.certificateSigned(keyStore, alias, newCerts);
}
} catch (Exception e) {
Log.error(e.getMessage(), e);
}
}
return true;
}
use of java.security.PrivateKey in project Openfire by igniterealtime.
the class CertificateManager method createX509V3Certificate.
/**
* Creates an X509 version3 certificate.
*
* @param kp KeyPair that keeps the public and private keys for the new certificate.
* @param days time to live
* @param issuerBuilder IssuerDN builder
* @param subjectBuilder SubjectDN builder
* @param domain Domain of the server.
* @param signAlgoritm Signature algorithm. This can be either a name or an OID.
* @return X509 V3 Certificate
* @throws GeneralSecurityException
* @throws IOException
*/
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
PublicKey pubKey = kp.getPublic();
PrivateKey privKey = kp.getPrivate();
byte[] serno = new byte[8];
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed((new Date().getTime()));
random.nextBytes(serno);
BigInteger serial = (new java.math.BigInteger(serno)).abs();
X500Name issuerDN = issuerBuilder.build();
X500Name subjectDN = subjectBuilder.build();
// builder
JcaX509v3CertificateBuilder certBuilder = new //
JcaX509v3CertificateBuilder(//
issuerDN, //
serial, //
new Date(), //
new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), //
subjectDN, //
pubKey);
// add subjectAlternativeName extension
boolean critical = subjectDN.getRDNs().length == 0;
ASN1Sequence othernameSequence = new DERSequence(new ASN1Encodable[] { new ASN1ObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERUTF8String(domain) });
GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAltNames);
// add keyIdentifiers extensions
JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));
try {
// build the certificate
ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
X509CertificateHolder cert = certBuilder.build(signer);
// verify the validity
if (!cert.isValidOn(new Date())) {
throw new GeneralSecurityException("Certificate validity not valid");
}
// verify the signature (self-signed)
ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
if (!cert.isSignatureValid(verifierProvider)) {
throw new GeneralSecurityException("Certificate signature not valid");
}
return new JcaX509CertificateConverter().getCertificate(cert);
} catch (OperatorCreationException | CertException e) {
throw new GeneralSecurityException(e);
}
}
Aggregations