use of java.security.PublicKey in project robovm by robovm.
the class ServerHandshakeImpl method processClientHello.
/**
*
* Processes Client Hello message.
* Server responds to client hello message with server hello
* and (if necessary) server certificate, server key exchange,
* certificate request, and server hello done messages.
*/
void processClientHello() {
CipherSuite cipher_suite;
// check that clientHello contains CompressionMethod.null
checkCompression: {
for (int i = 0; i < clientHello.compression_methods.length; i++) {
if (clientHello.compression_methods[i] == 0) {
break checkCompression;
}
}
fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE. Incorrect client hello message");
}
byte[] server_version = clientHello.client_version;
if (!ProtocolVersion.isSupported(clientHello.client_version)) {
if (clientHello.client_version[0] >= 3) {
// Protocol from the future, admit that the newest thing we know is TLSv1
server_version = ProtocolVersion.TLSv1.version;
} else {
fatalAlert(AlertProtocol.PROTOCOL_VERSION, "PROTOCOL VERSION. Unsupported client version " + clientHello.client_version[0] + clientHello.client_version[1]);
}
}
isResuming = false;
FIND: if (clientHello.session_id.length != 0) {
// client wishes to reuse session
SSLSessionImpl sessionToResume;
boolean reuseCurrent = false;
// reuse current session
if (session != null && Arrays.equals(session.id, clientHello.session_id)) {
if (session.isValid()) {
isResuming = true;
break FIND;
}
reuseCurrent = true;
}
// find session in cash
sessionToResume = findSessionToResume(clientHello.session_id);
if (sessionToResume == null || !sessionToResume.isValid()) {
if (!parameters.getEnableSessionCreation()) {
if (reuseCurrent) {
// we can continue current session
sendWarningAlert(AlertProtocol.NO_RENEGOTIATION);
status = NOT_HANDSHAKING;
clearMessages();
return;
}
// throw AlertException
fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "SSL Session may not be created");
}
session = null;
} else {
session = (SSLSessionImpl) sessionToResume.clone();
isResuming = true;
}
}
if (isResuming) {
cipher_suite = session.cipherSuite;
// clientHello.cipher_suites must include at least cipher_suite from the session
checkCipherSuite: {
for (int i = 0; i < clientHello.cipher_suites.length; i++) {
if (cipher_suite.equals(clientHello.cipher_suites[i])) {
break checkCipherSuite;
}
}
fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE. Incorrect client hello message");
}
} else {
cipher_suite = selectSuite(clientHello.cipher_suites);
if (cipher_suite == null) {
fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE. NO COMMON SUITE");
}
if (!parameters.getEnableSessionCreation()) {
fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "SSL Session may not be created");
}
session = new SSLSessionImpl(cipher_suite, parameters.getSecureRandom());
if (engineOwner != null) {
session.setPeer(engineOwner.getPeerHost(), engineOwner.getPeerPort());
} else {
session.setPeer(socketOwner.getInetAddress().getHostName(), socketOwner.getPort());
}
}
recordProtocol.setVersion(server_version);
session.protocol = ProtocolVersion.getByVersion(server_version);
session.clientRandom = clientHello.random;
// create server hello message
serverHello = new ServerHello(parameters.getSecureRandom(), server_version, session.getId(), cipher_suite, //CompressionMethod.null
(byte) 0);
session.serverRandom = serverHello.random;
send(serverHello);
if (isResuming) {
sendChangeCipherSpec();
return;
}
// create and send server certificate message if needed
if (!cipher_suite.isAnonymous()) {
// need to send server certificate
X509Certificate[] certs = null;
String certType = cipher_suite.getServerKeyType();
if (certType == null) {
fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "NO CERT TYPE FOR " + cipher_suite.getName());
}
// obtain certificates from key manager
String alias = null;
X509KeyManager km = parameters.getKeyManager();
if (km instanceof X509ExtendedKeyManager) {
X509ExtendedKeyManager ekm = (X509ExtendedKeyManager) km;
if (this.socketOwner != null) {
alias = ekm.chooseServerAlias(certType, null, this.socketOwner);
} else {
alias = ekm.chooseEngineServerAlias(certType, null, this.engineOwner);
}
if (alias != null) {
certs = ekm.getCertificateChain(alias);
}
} else {
alias = km.chooseServerAlias(certType, null, this.socketOwner);
if (alias != null) {
certs = km.getCertificateChain(alias);
}
}
if (certs == null) {
fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "NO SERVER CERTIFICATE FOUND");
return;
}
session.localCertificates = certs;
serverCert = new CertificateMessage(certs);
privKey = km.getPrivateKey(alias);
send(serverCert);
}
// create and send server key exchange message if needed
RSAPublicKey rsakey = null;
DHPublicKeySpec dhkeySpec = null;
byte[] hash = null;
BigInteger p = null;
BigInteger g = null;
KeyPairGenerator kpg = null;
try {
if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
PublicKey pk = serverCert.certs[0].getPublicKey();
if (getRSAKeyLength(pk) > 512) {
// key is longer than 512 bits
kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512);
}
} else if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_DSS || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_DSS_EXPORT || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_RSA || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_RSA_EXPORT || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DH_anon || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DH_anon_EXPORT) {
kpg = KeyPairGenerator.getInstance("DH");
p = new BigInteger(1, DHParameters.getPrime());
g = new BigInteger("2");
DHParameterSpec spec = new DHParameterSpec(p, g);
kpg.initialize(spec);
}
} catch (Exception e) {
fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
}
if (kpg != null) {
// need to send server key exchange message
DigitalSignature ds = new DigitalSignature(cipher_suite.authType);
KeyPair kp = null;
try {
kp = kpg.genKeyPair();
if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
rsakey = (RSAPublicKey) kp.getPublic();
} else {
DHPublicKey dhkey = (DHPublicKey) kp.getPublic();
KeyFactory kf = KeyFactory.getInstance("DH");
dhkeySpec = kf.getKeySpec(dhkey, DHPublicKeySpec.class);
}
if (!cipher_suite.isAnonymous()) {
// calculate signed_params
// init by private key which correspond to
// server certificate
ds.init(privKey);
// use emphemeral key for key exchange
privKey = kp.getPrivate();
ds.update(clientHello.getRandom());
ds.update(serverHello.getRandom());
//FIXME 1_byte==0x00
if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
ServerKeyExchange.updateSignatureRsa(ds, rsakey.getModulus(), rsakey.getPublicExponent());
} else {
ServerKeyExchange.updateSignatureDh(ds, dhkeySpec.getP(), dhkeySpec.getG(), dhkeySpec.getY());
}
hash = ds.sign();
} else {
// use emphemeral key for key exchange
privKey = kp.getPrivate();
}
} catch (Exception e) {
fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
}
if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
serverKeyExchange = new ServerKeyExchange(rsakey.getModulus(), rsakey.getPublicExponent(), null, hash);
} else {
serverKeyExchange = new ServerKeyExchange(p, g, dhkeySpec.getY(), hash);
}
send(serverKeyExchange);
}
// CERTIFICATE_REQUEST
certRequest: if (parameters.getWantClientAuth() || parameters.getNeedClientAuth()) {
X509Certificate[] accepted;
try {
X509TrustManager tm = parameters.getTrustManager();
accepted = tm.getAcceptedIssuers();
} catch (ClassCastException e) {
// don't send certificateRequest
break certRequest;
}
byte[] requestedClientCertTypes = { CipherSuite.TLS_CT_RSA_SIGN, CipherSuite.TLS_CT_DSS_SIGN };
certificateRequest = new CertificateRequest(requestedClientCertTypes, accepted);
send(certificateRequest);
}
// SERVER_HELLO_DONE
serverHelloDone = new ServerHelloDone();
send(serverHelloDone);
status = NEED_UNWRAP;
}
use of java.security.PublicKey in project robovm by robovm.
the class X509CertSelectorTest method test_setSubjectPublicKeyAlgIDLjava_lang_String.
/**
* java.security.cert.X509CertSelector#setSubjectPublicKeyAlgID(java.lang.String)
*/
public void test_setSubjectPublicKeyAlgIDLjava_lang_String() throws Exception {
X509CertSelector selector = new X509CertSelector();
// RSA (source:
String pkaid1 = "1.2.840.113549.1.1.1";
// http://asn1.elibel.tm.fr)
// DSA (source:
String pkaid2 = "1.2.840.10040.4.1";
// http://asn1.elibel.tm.fr)
PublicKey pkey1 = new TestKeyPair("RSA").getPublic();
;
PublicKey pkey2 = new TestKeyPair("DSA").getPublic();
;
TestCert cert1 = new TestCert(pkey1);
TestCert cert2 = new TestCert(pkey2);
selector.setSubjectPublicKeyAlgID(null);
assertTrue("Any certificate should match in the case of null " + "subjectPublicKeyAlgID criteria.", selector.match(cert1) && selector.match(cert2));
String[] validOIDs = { "0.0.20", "1.25.0", "2.0.39", "0.2.10", "1.35.15", "2.17.89", "2.5.29.16", "2.5.29.17", "2.5.29.30", "2.5.29.32", "2.5.29.37" };
for (int i = 0; i < validOIDs.length; i++) {
selector.setSubjectPublicKeyAlgID(validOIDs[i]);
assertEquals(validOIDs[i], selector.getSubjectPublicKeyAlgID());
}
String[] invalidOIDs = { "0.20", "1.25", "2.39", "3.10" };
for (int i = 0; i < invalidOIDs.length; i++) {
try {
selector.setSubjectPublicKeyAlgID(invalidOIDs[i]);
fail("IOException wasn't thrown for " + invalidOIDs[i]);
} catch (IOException expected) {
}
}
selector.setSubjectPublicKeyAlgID(pkaid1);
assertTrue("The certificate should match the selection criteria.", selector.match(cert1));
assertFalse("The certificate should not match the selection criteria.", selector.match(cert2));
selector.setSubjectPublicKeyAlgID(pkaid2);
assertTrue("The certificate should match the selection criteria.", selector.match(cert2));
}
use of java.security.PublicKey in project robovm by robovm.
the class TrustAnchorTest method testGetTrustedCer02.
/**
* Test #2 for <code>getCAName()</code> method<br>
*
* Assertion: returns ... <code>null</code> if <code>TrustAnchor</code>
* was not specified as trusted certificate<br>
* Test preconditions: test object is not specified as trusted certificate<br>
* Expected: <code>null</code> as return value<br>
* @throws InvalidKeySpecException
*/
public final void testGetTrustedCer02() throws Exception {
PublicKey pk = new TestKeyPair(keyAlg).getPublic();
// sub testcase 1
TrustAnchor ta = new TrustAnchor(validCaNameRfc2253, pk, null);
assertNull("null1", ta.getTrustedCert());
// sub testcase 2
X500Principal x500p = new X500Principal(validCaNameRfc2253);
ta = new TrustAnchor(x500p, pk, null);
assertNull("null2", ta.getTrustedCert());
X509Certificate cert = new TestCertUtils.TestX509Certificate(x500p, x500p);
TrustAnchor ta2 = new TrustAnchor(cert, null);
assertSame(cert, ta2.getTrustedCert());
}
use of java.security.PublicKey in project robovm by robovm.
the class TrustAnchorTest method testToString.
/**
* Test #1 for <code>toString()</code> method<br>
*
* Assertion: returns a formatted string describing the TrustAnchor<br>
* Test preconditions: valid parameters are passed to the constructors<br>
* Expected: not null string<br>
*/
public final void testToString() throws Exception {
PublicKey pk = new TestKeyPair(keyAlg).getPublic();
TrustAnchor ta1 = new TrustAnchor(validCaNameRfc2253, pk, getFullEncoding());
assertNotNull(ta1.toString());
X500Principal x500p = new X500Principal(validCaNameRfc2253);
TrustAnchor ta2 = new TrustAnchor(x500p, pk, getEncodingNoMinMax());
assertNotNull(ta2.toString());
CertificateFactory certFact = CertificateFactory.getInstance("X509");
X509Certificate pemCert = (X509Certificate) certFact.generateCertificate(new ByteArrayInputStream(TestUtils.getX509Certificate_v3()));
TrustAnchor ta3 = new TrustAnchor(pemCert, getEncodingPSOnly());
assertNotNull(ta3.toString());
}
use of java.security.PublicKey in project robovm by robovm.
the class TrustAnchorTest method testTrustAnchorStringPublicKeybyteArray04.
/**
* Test #4 for <code>TrustAnchor(String, PublicKey, byte[])</code> constructor<br>
* Assertion: <code>NullPointerException</code> if <code>caName</code>
* or <code>caPublicKey</code> parameter is <code>null</code><br>
* Test preconditions: pass <code>null</code> as mentioned parameter<br>
* Expected: NullPointerException
*/
public final void testTrustAnchorStringPublicKeybyteArray04() throws Exception {
PublicKey pk = new TestKeyPair(keyAlg).getPublic();
// sub testcase 1: 'caName' param is null
try {
new TrustAnchor((String) null, pk, getEncodingPSOnly());
fail("NullPointerException has not been thrown");
} catch (NullPointerException ok) {
}
// sub testcase 2: 'caPublicKey' param is null
try {
new TrustAnchor(validCaNameRfc2253, null, getEncodingPSOnly());
fail("NullPointerException has not been thrown");
} catch (NullPointerException ok) {
}
// sub testcase 3: 'caName' and 'caPublicKey' params are null
try {
new TrustAnchor((String) null, null, getEncodingPSOnly());
fail("NullPointerException has not been thrown");
} catch (NullPointerException ok) {
}
// sub testcase 4: 'caName' param is empty
try {
new TrustAnchor("", pk, getEncodingPSOnly());
fail("IllegalArgumentException has not been thrown");
} catch (IllegalArgumentException ok) {
}
// sub testcase 5: 'caName' param is incorrect distinguished name
try {
new TrustAnchor("AID.11.12=A", pk, getEncodingPSOnly());
fail("IllegalArgumentException has not been thrown");
} catch (IllegalArgumentException ok) {
}
}
Aggregations