use of java.security.PrivateKey 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.PrivateKey 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.PrivateKey in project robovm by robovm.
the class OpenSSLServerSocketImpl method checkForPrivateKey.
private boolean checkForPrivateKey(String keyType, Class<?> keyClass) {
String alias = sslParameters.getKeyManager().chooseServerAlias(keyType, null, null);
if (alias == null) {
return false;
}
PrivateKey key = sslParameters.getKeyManager().getPrivateKey(alias);
return (key != null && keyClass.isAssignableFrom(key.getClass()));
}
use of java.security.PrivateKey in project robovm by robovm.
the class OpenSSLSocketImpl method setCertificate.
private void setCertificate(String alias) throws CertificateEncodingException, SSLException {
if (alias == null) {
return;
}
PrivateKey privateKey = sslParameters.getKeyManager().getPrivateKey(alias);
if (privateKey == null) {
return;
}
X509Certificate[] certificates = sslParameters.getKeyManager().getCertificateChain(alias);
if (certificates == null) {
return;
}
// Note that OpenSSL says to use SSL_use_certificate before SSL_use_PrivateKey.
byte[][] certificateBytes = NativeCrypto.encodeCertificates(certificates);
NativeCrypto.SSL_use_certificate(sslNativePointer, certificateBytes);
try {
final OpenSSLKey key = OpenSSLKey.fromPrivateKey(privateKey);
NativeCrypto.SSL_use_PrivateKey(sslNativePointer, key.getPkeyContext());
} catch (InvalidKeyException e) {
throw new SSLException(e);
}
// checks the last installed private key and certificate,
// so need to do this once per loop iteration
NativeCrypto.SSL_check_private_key(sslNativePointer);
}
use of java.security.PrivateKey in project robovm by robovm.
the class OpenSSLECKeyFactory method engineTranslateKey.
@Override
protected Key engineTranslateKey(Key key) throws InvalidKeyException {
if (key == null) {
throw new InvalidKeyException("key == null");
}
if ((key instanceof OpenSSLECPublicKey) || (key instanceof OpenSSLECPrivateKey)) {
return key;
} else if (key instanceof ECPublicKey) {
ECPublicKey ecKey = (ECPublicKey) key;
ECPoint w = ecKey.getW();
ECParameterSpec params = ecKey.getParams();
try {
return engineGeneratePublic(new ECPublicKeySpec(w, params));
} catch (InvalidKeySpecException e) {
throw new InvalidKeyException(e);
}
} else if (key instanceof ECPrivateKey) {
ECPrivateKey ecKey = (ECPrivateKey) key;
BigInteger s = ecKey.getS();
ECParameterSpec params = ecKey.getParams();
try {
return engineGeneratePrivate(new ECPrivateKeySpec(s, params));
} catch (InvalidKeySpecException e) {
throw new InvalidKeyException(e);
}
} else if ((key instanceof PrivateKey) && ("PKCS#8".equals(key.getFormat()))) {
byte[] encoded = key.getEncoded();
if (encoded == null) {
throw new InvalidKeyException("Key does not support encoding");
}
try {
return engineGeneratePrivate(new PKCS8EncodedKeySpec(encoded));
} catch (InvalidKeySpecException e) {
throw new InvalidKeyException(e);
}
} else if ((key instanceof PublicKey) && ("X.509".equals(key.getFormat()))) {
byte[] encoded = key.getEncoded();
if (encoded == null) {
throw new InvalidKeyException("Key does not support encoding");
}
try {
return engineGeneratePublic(new X509EncodedKeySpec(encoded));
} catch (InvalidKeySpecException e) {
throw new InvalidKeyException(e);
}
} else {
throw new InvalidKeyException("Key must be EC public or private key; was " + key.getClass().getName());
}
}
Aggregations