use of javax.crypto.spec.DHParameterSpec in project XobotOS by xamarin.
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");
}
if (!ProtocolVersion.isSupported(clientHello.client_version)) {
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(clientHello.client_version);
session.protocol = ProtocolVersion.getByVersion(clientHello.client_version);
session.clientRandom = clientHello.random;
// create server hello message
serverHello = new ServerHello(parameters.getSecureRandom(), clientHello.client_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());
byte[] tmp;
byte[] tmpLength = new byte[2];
//FIXME 1_byte==0x00
if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
tmp = ServerKeyExchange.toUnsignedByteArray(rsakey.getModulus());
tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
tmpLength[1] = (byte) (tmp.length & 0xFF);
ds.update(tmpLength);
ds.update(tmp);
tmp = ServerKeyExchange.toUnsignedByteArray(rsakey.getPublicExponent());
tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
tmpLength[1] = (byte) (tmp.length & 0xFF);
ds.update(tmpLength);
ds.update(tmp);
} else {
tmp = ServerKeyExchange.toUnsignedByteArray(dhkeySpec.getP());
tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
tmpLength[1] = (byte) (tmp.length & 0xFF);
ds.update(tmpLength);
ds.update(tmp);
tmp = ServerKeyExchange.toUnsignedByteArray(dhkeySpec.getG());
tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
tmpLength[1] = (byte) (tmp.length & 0xFF);
ds.update(tmpLength);
ds.update(tmp);
tmp = ServerKeyExchange.toUnsignedByteArray(dhkeySpec.getY());
tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
tmpLength[1] = (byte) (tmp.length & 0xFF);
ds.update(tmpLength);
ds.update(tmp);
}
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 javax.crypto.spec.DHParameterSpec in project jdk8u_jdk by JetBrains.
the class KAParticipant method runTest.
public static boolean runTest(String algo, int numParties, String secretAlgo) {
KAParticipant[] parties = new KAParticipant[numParties];
Key[] keyArchives = new Key[numParties];
try {
// generate AlogirhtmParameterSpec
AlgorithmParameterGenerator apg = AlgorithmParameterGenerator.getInstance("DH", "SunJCE");
AlgorithmParameterSpec aps = new DHGenParameterSpec(512, 64);
apg.init(aps);
DHParameterSpec spec = apg.generateParameters().getParameterSpec(DHParameterSpec.class);
//initilize all KeyAgreement participants
for (int i = 0; i < numParties; i++) {
parties[i] = new KAParticipant(PA_NAMES[i], algo);
parties[i].initialize(spec);
keyArchives[i] = parties[i].getPublicKey();
}
// Do all phases in the KeyAgreement for all participants
Key[] keyBuffer = new Key[numParties];
boolean lastPhase = false;
for (int j = 0; j < numParties - 1; j++) {
if (j == numParties - 2) {
lastPhase = true;
}
for (int k = 0; k < numParties; k++) {
if (k == numParties - 1) {
keyBuffer[k] = parties[k].doPhase(keyArchives[0], lastPhase);
} else {
keyBuffer[k] = parties[k].doPhase(keyArchives[k + 1], lastPhase);
}
}
System.arraycopy(keyBuffer, 0, keyArchives, 0, numParties);
}
//Comparison: The secret keys generated by all involved parties should be the same
SecretKey[] sKeys = new SecretKey[numParties];
for (int n = 0; n < numParties; n++) {
sKeys[n] = parties[n].generateSecret(secretAlgo);
}
for (int q = 0; q < numParties - 1; q++) {
if (!Arrays.equals(sKeys[q].getEncoded(), sKeys[q + 1].getEncoded())) {
return false;
}
}
return true;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
use of javax.crypto.spec.DHParameterSpec in project geode by apache.
the class HandShake method initDHKeys.
/**
* Initialize the Diffie-Hellman keys. This method is not thread safe
*/
public static void initDHKeys(DistributionConfig config) throws Exception {
dhSKAlgo = config.getSecurityClientDHAlgo();
dhPrivateKey = null;
dhPublicKey = null;
// that has authenticator defined.
if ((dhSKAlgo != null && dhSKAlgo.length() > 0) || securityService.isClientSecurityRequired()) {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
DHParameterSpec dhSpec = new DHParameterSpec(dhP, dhG, dhL);
keyGen.initialize(dhSpec);
KeyPair keypair = keyGen.generateKeyPair();
// Get the generated public and private keys
dhPrivateKey = keypair.getPrivate();
dhPublicKey = keypair.getPublic();
random = new SecureRandom();
// Force the random generator to seed itself.
byte[] someBytes = new byte[48];
random.nextBytes(someBytes);
}
}
use of javax.crypto.spec.DHParameterSpec in project geode by apache.
the class GMSEncryptJUnitTest method testDHAlgo3.
@Test
public void testDHAlgo3() throws Exception {
DHParameterSpec dhSkipParamSpec;
System.out.println("Using SKIP Diffie-Hellman parameters");
dhSkipParamSpec = new DHParameterSpec(skip1024Modulus, skip1024Base);
// Alice creates her own DH key pair
System.out.println("ALICE: Generate DH keypair ...");
KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
aliceKpairGen.initialize(dhSkipParamSpec);
KeyPair aliceKpair = aliceKpairGen.generateKeyPair();
// Bob creates his own DH key pair
System.out.println("BOB: Generate DH keypair ...");
KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
bobKpairGen.initialize(dhSkipParamSpec);
KeyPair bobKpair = bobKpairGen.generateKeyPair();
// Alice initialize
System.out.println("ALICE: Initialize ...");
KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
aliceKeyAgree.init(aliceKpair.getPrivate());
// Bob initialize
System.out.println("BOB : Initialize ...");
KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
bobKeyAgree.init(bobKpair.getPrivate());
// Alice uses Carol's public key
aliceKeyAgree.doPhase(bobKpair.getPublic(), true);
// Bob uses Alice's public key
bobKeyAgree.doPhase(aliceKpair.getPublic(), true);
String dhKalgo = "AES";
// Alice, Bob and Carol compute their secrets
SecretKey aliceSharedSecret = aliceKeyAgree.generateSecret(dhKalgo);
System.out.println("Alice secret: " + toHexString(aliceSharedSecret.getEncoded()));
SecretKey bobSharedSecret = bobKeyAgree.generateSecret(dhKalgo);
System.out.println("Bob secret: " + toHexString(bobSharedSecret.getEncoded()));
// Compare Alice and Bob
if (!java.util.Arrays.equals(aliceSharedSecret.getEncoded(), bobSharedSecret.getEncoded()))
throw new Exception("Alice and Bob differ");
System.out.println("Alice and Bob are the same");
}
use of javax.crypto.spec.DHParameterSpec in project geode by apache.
the class GMSEncryptJUnitTest method testDHAlgo.
@Test
public void testDHAlgo() throws Exception {
DHParameterSpec dhSkipParamSpec;
System.out.println("Using SKIP Diffie-Hellman parameters");
dhSkipParamSpec = new DHParameterSpec(skip1024Modulus, skip1024Base);
// Alice creates her own DH key pair
System.out.println("ALICE: Generate DH keypair ...");
KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
aliceKpairGen.initialize(dhSkipParamSpec);
KeyPair aliceKpair = aliceKpairGen.generateKeyPair();
// Bob creates his own DH key pair
System.out.println("BOB: Generate DH keypair ...");
KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
bobKpairGen.initialize(dhSkipParamSpec);
KeyPair bobKpair = bobKpairGen.generateKeyPair();
// Carol creates her own DH key pair
System.out.println("CAROL: Generate DH keypair ...");
KeyPairGenerator carolKpairGen = KeyPairGenerator.getInstance("DH");
carolKpairGen.initialize(dhSkipParamSpec);
KeyPair carolKpair = carolKpairGen.generateKeyPair();
// Alice initialize
System.out.println("ALICE: Initialize ...");
KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
aliceKeyAgree.init(aliceKpair.getPrivate());
// Bob initialize
System.out.println("BOB: Initialize ...");
KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
bobKeyAgree.init(bobKpair.getPrivate());
// Carol initialize
System.out.println("CAROL: Initialize ...");
KeyAgreement carolKeyAgree = KeyAgreement.getInstance("DH");
carolKeyAgree.init(carolKpair.getPrivate());
// Alice uses Carol's public key
Key ac = aliceKeyAgree.doPhase(carolKpair.getPublic(), false);
// Bob uses Alice's public key
Key ba = bobKeyAgree.doPhase(aliceKpair.getPublic(), false);
// Carol uses Bob's public key
Key cb = carolKeyAgree.doPhase(bobKpair.getPublic(), false);
// Alice uses Carol's result from above
aliceKeyAgree.doPhase(cb, true);
// Bob uses Alice's result from above
bobKeyAgree.doPhase(ac, true);
// Carol uses Bob's result from above
carolKeyAgree.doPhase(ba, true);
// Alice, Bob and Carol compute their secrets
byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
System.out.println("Alice secret: " + toHexString(aliceSharedSecret));
byte[] bobSharedSecret = bobKeyAgree.generateSecret();
System.out.println("Bob secret: " + toHexString(bobSharedSecret));
byte[] carolSharedSecret = carolKeyAgree.generateSecret();
System.out.println("Carol secret: " + toHexString(carolSharedSecret));
// Compare Alice and Bob
if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret))
throw new Exception("Alice and Bob differ");
System.out.println("Alice and Bob are the same");
// Compare Bob and Carol
if (!java.util.Arrays.equals(bobSharedSecret, carolSharedSecret))
throw new Exception("Bob and Carol differ");
System.out.println("Bob and Carol are the same");
}
Aggregations