use of java.security.KeyFactory in project robovm by robovm.
the class TestKeyStore method createCertificate.
private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey, X500Principal subject, X500Principal issuer, int keyUsage, boolean ca, List<KeyPurposeId> extendedKeyUsages, List<Boolean> criticalExtendedKeyUsages, List<GeneralName> subjectAltNames, List<GeneralSubtree> permittedNameConstraints, List<GeneralSubtree> excludedNameConstraints) throws Exception {
// Note that there is no way to programmatically make a
// Certificate using java.* or javax.* APIs. The
// CertificateFactory interface assumes you want to read
// in a stream of bytes, typically the X.509 factory would
// allow ASN.1 DER encoded bytes and optionally some PEM
// formats. Here we use Bouncy Castle's
// X509V3CertificateGenerator and related classes.
long millisPerDay = 24 * 60 * 60 * 1000;
long now = System.currentTimeMillis();
Date start = new Date(now - millisPerDay);
Date end = new Date(now + millisPerDay);
BigInteger serial = BigInteger.valueOf(1);
String keyAlgorithm = privateKey.getAlgorithm();
String signatureAlgorithm;
if (keyAlgorithm.equals("RSA")) {
signatureAlgorithm = "sha1WithRSA";
} else if (keyAlgorithm.equals("DSA")) {
signatureAlgorithm = "sha1WithDSA";
} else if (keyAlgorithm.equals("EC")) {
signatureAlgorithm = "sha1WithECDSA";
} else if (keyAlgorithm.equals("EC_RSA")) {
signatureAlgorithm = "sha1WithRSA";
} else {
throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
}
X509V3CertificateGenerator x509cg = new X509V3CertificateGenerator();
x509cg.setSubjectDN(subject);
x509cg.setIssuerDN(issuer);
x509cg.setNotBefore(start);
x509cg.setNotAfter(end);
x509cg.setPublicKey(publicKey);
x509cg.setSignatureAlgorithm(signatureAlgorithm);
x509cg.setSerialNumber(serial);
if (keyUsage != 0) {
x509cg.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage));
}
if (ca) {
x509cg.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
}
for (int i = 0; i < extendedKeyUsages.size(); i++) {
KeyPurposeId keyPurposeId = extendedKeyUsages.get(i);
boolean critical = criticalExtendedKeyUsages.get(i);
x509cg.addExtension(X509Extensions.ExtendedKeyUsage, critical, new ExtendedKeyUsage(keyPurposeId));
}
for (GeneralName subjectAltName : subjectAltNames) {
x509cg.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(subjectAltName).getEncoded());
}
if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
x509cg.addExtension(X509Extensions.NameConstraints, true, new NameConstraints(permittedNameConstraints.toArray(new GeneralSubtree[permittedNameConstraints.size()]), excludedNameConstraints.toArray(new GeneralSubtree[excludedNameConstraints.size()])));
}
if (privateKey instanceof ECPrivateKey) {
/*
* bouncycastle needs its own ECPrivateKey implementation
*/
KeyFactory kf = KeyFactory.getInstance(keyAlgorithm, "BC");
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(privateKey.getEncoded());
privateKey = kf.generatePrivate(ks);
}
X509Certificate x509c = x509cg.generateX509Certificate(privateKey);
if (StandardNames.IS_RI) {
/*
* The RI can't handle the BC EC signature algorithm
* string of "ECDSA", since it expects "...WITHEC...",
* so convert from BC to RI X509Certificate
* implementation via bytes.
*/
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
Certificate c = cf.generateCertificate(bais);
x509c = (X509Certificate) c;
}
return x509c;
}
use of java.security.KeyFactory in project robovm by robovm.
the class RandomPrivateKeyX509ExtendedKeyManager method getPrivateKey.
@Override
public PrivateKey getPrivateKey(String alias) {
PrivateKey originalPrivateKey = super.getPrivateKey(alias);
if (originalPrivateKey == null) {
return null;
}
PrivateKey result;
String keyAlgorithm = originalPrivateKey.getAlgorithm();
try {
KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
if ("RSA".equals(keyAlgorithm)) {
RSAPrivateKeySpec originalKeySpec = keyFactory.getKeySpec(originalPrivateKey, RSAPrivateKeySpec.class);
int keyLengthBits = originalKeySpec.getModulus().bitLength();
// Use a cache because RSA key generation is slow.
String cacheKey = keyAlgorithm + "-" + keyLengthBits;
result = cachedKeys.get(cacheKey);
if (result == null) {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyAlgorithm);
keyPairGenerator.initialize(keyLengthBits);
result = keyPairGenerator.generateKeyPair().getPrivate();
cachedKeys.put(cacheKey, result);
}
} else if ("DSA".equals(keyAlgorithm)) {
DSAPrivateKeySpec originalKeySpec = keyFactory.getKeySpec(originalPrivateKey, DSAPrivateKeySpec.class);
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyAlgorithm);
keyPairGenerator.initialize(new DSAParameterSpec(originalKeySpec.getP(), originalKeySpec.getQ(), originalKeySpec.getG()));
result = keyPairGenerator.generateKeyPair().getPrivate();
} else {
Assert.fail("Unsupported key algorithm: " + originalPrivateKey.getAlgorithm());
result = null;
}
} catch (GeneralSecurityException e) {
Assert.fail("Failed to generate private key: " + e);
result = null;
}
return result;
}
use of java.security.KeyFactory in project robovm by robovm.
the class ClientHandshakeImpl method processServerHelloDone.
/**
* Processes ServerHelloDone: makes verification of the server messages; sends
* client messages, computers masterSecret, sends ChangeCipherSpec
*/
void processServerHelloDone() {
PrivateKey clientKey = null;
if (serverCert != null) {
if (session.cipherSuite.isAnonymous()) {
unexpectedMessage();
return;
}
verifyServerCert();
} else {
if (!session.cipherSuite.isAnonymous()) {
unexpectedMessage();
return;
}
}
// Client certificate
if (certificateRequest != null) {
X509Certificate[] certs = null;
// obtain certificates from key manager
String alias = null;
String[] certTypes = certificateRequest.getTypesAsString();
X500Principal[] issuers = certificateRequest.certificate_authorities;
X509KeyManager km = parameters.getKeyManager();
if (km instanceof X509ExtendedKeyManager) {
X509ExtendedKeyManager ekm = (X509ExtendedKeyManager) km;
if (this.socketOwner != null) {
alias = ekm.chooseClientAlias(certTypes, issuers, this.socketOwner);
} else {
alias = ekm.chooseEngineClientAlias(certTypes, issuers, this.engineOwner);
}
if (alias != null) {
certs = ekm.getCertificateChain(alias);
}
} else {
alias = km.chooseClientAlias(certTypes, issuers, this.socketOwner);
if (alias != null) {
certs = km.getCertificateChain(alias);
}
}
session.localCertificates = certs;
clientCert = new CertificateMessage(certs);
clientKey = km.getPrivateKey(alias);
send(clientCert);
}
// Client key exchange
if (session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
// RSA encrypted premaster secret message
Cipher c;
try {
c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
if (serverKeyExchange != null) {
if (!session.cipherSuite.isAnonymous()) {
DigitalSignature ds = new DigitalSignature(serverCert.getAuthType());
ds.init(serverCert.certs[0]);
ds.update(clientHello.getRandom());
ds.update(serverHello.getRandom());
if (!serverKeyExchange.verifySignature(ds)) {
fatalAlert(AlertProtocol.DECRYPT_ERROR, "Cannot verify RSA params");
return;
}
}
c.init(Cipher.WRAP_MODE, serverKeyExchange.getRSAPublicKey());
} else {
c.init(Cipher.WRAP_MODE, serverCert.certs[0]);
}
} catch (Exception e) {
fatalAlert(AlertProtocol.INTERNAL_ERROR, "Unexpected exception", e);
return;
}
preMasterSecret = new byte[48];
parameters.getSecureRandom().nextBytes(preMasterSecret);
System.arraycopy(clientHello.client_version, 0, preMasterSecret, 0, 2);
try {
clientKeyExchange = new ClientKeyExchange(c.wrap(new SecretKeySpec(preMasterSecret, "preMasterSecret")), serverHello.server_version[1] == 1);
} catch (Exception e) {
fatalAlert(AlertProtocol.INTERNAL_ERROR, "Unexpected exception", e);
return;
}
} else if (session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_DSS || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_DSS_EXPORT || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_RSA || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_RSA_EXPORT || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DH_anon || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DH_anon_EXPORT) {
/*
* All other key exchanges should have had a DH key communicated via
* ServerKeyExchange beforehand.
*/
if (serverKeyExchange == null) {
fatalAlert(AlertProtocol.UNEXPECTED_MESSAGE, "Expected ServerKeyExchange");
return;
}
if (session.cipherSuite.isAnonymous() != serverKeyExchange.isAnonymous()) {
fatalAlert(AlertProtocol.DECRYPT_ERROR, "Wrong type in ServerKeyExchange");
return;
}
try {
if (!session.cipherSuite.isAnonymous()) {
DigitalSignature ds = new DigitalSignature(serverCert.getAuthType());
ds.init(serverCert.certs[0]);
ds.update(clientHello.getRandom());
ds.update(serverHello.getRandom());
if (!serverKeyExchange.verifySignature(ds)) {
fatalAlert(AlertProtocol.DECRYPT_ERROR, "Cannot verify DH params");
return;
}
}
KeyFactory kf = KeyFactory.getInstance("DH");
KeyAgreement agreement = KeyAgreement.getInstance("DH");
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
PublicKey serverDhPublic = kf.generatePublic(new DHPublicKeySpec(serverKeyExchange.par3, serverKeyExchange.par1, serverKeyExchange.par2));
DHParameterSpec spec = new DHParameterSpec(serverKeyExchange.par1, serverKeyExchange.par2);
kpg.initialize(spec);
KeyPair kp = kpg.generateKeyPair();
DHPublicKey pubDhKey = (DHPublicKey) kp.getPublic();
clientKeyExchange = new ClientKeyExchange(pubDhKey.getY());
PrivateKey privDhKey = kp.getPrivate();
agreement.init(privDhKey);
agreement.doPhase(serverDhPublic, true);
preMasterSecret = agreement.generateSecret();
} catch (Exception e) {
fatalAlert(AlertProtocol.INTERNAL_ERROR, "Unexpected exception", e);
return;
}
} else {
fatalAlert(AlertProtocol.DECRYPT_ERROR, "Unsupported handshake type");
return;
}
if (clientKeyExchange != null) {
send(clientKeyExchange);
}
computerMasterSecret();
// fixed DH parameters
if (clientCert != null && clientCert.certs.length > 0 && !clientKeyExchange.isEmpty()) {
// Certificate verify
String authType = clientKey.getAlgorithm();
DigitalSignature ds = new DigitalSignature(authType);
ds.init(clientKey);
if ("RSA".equals(authType)) {
ds.setMD5(io_stream.getDigestMD5());
ds.setSHA(io_stream.getDigestSHA());
} else if ("DSA".equals(authType)) {
ds.setSHA(io_stream.getDigestSHA());
// The Signature should be empty in case of anonymous signature algorithm:
// } else if ("DH".equals(authType)) {
}
certificateVerify = new CertificateVerify(ds.sign());
send(certificateVerify);
}
sendChangeCipherSpec();
}
use of java.security.KeyFactory in project robovm by robovm.
the class RSAPrivateCrtKeyTest method setUp.
protected void setUp() throws Exception {
super.setUp();
KeyFactory gen = KeyFactory.getInstance("RSA");
key = (RSAPrivateCrtKey) gen.generatePrivate(Util.rsaCrtParam);
}
use of java.security.KeyFactory in project robovm by robovm.
the class RSAPrivateKeyTest method test_getPrivateExponent.
/**
* java.security.interfaces.RSAPrivateKey
* #getPrivateExponent()
*/
public void test_getPrivateExponent() throws Exception {
KeyFactory gen = KeyFactory.getInstance("RSA");
final BigInteger n = BigInteger.valueOf(3233);
final BigInteger d = BigInteger.valueOf(2753);
RSAPrivateKey key = (RSAPrivateKey) gen.generatePrivate(new RSAPrivateKeySpec(n, d));
assertEquals("invalid private exponent", d, key.getPrivateExponent());
}
Aggregations