use of java.security.SecureRandom in project XobotOS by xamarin.
the class OpenSSLSocketImpl method startHandshake.
/**
* Perform the handshake
*
* @param full If true, disable handshake cutthrough for a fully synchronous handshake
*/
public synchronized void startHandshake(boolean full) throws IOException {
synchronized (handshakeLock) {
checkOpen();
if (!handshakeStarted) {
handshakeStarted = true;
} else {
return;
}
}
// note that this modifies the global seed, not something specific to the connection
final int seedLengthInBytes = NativeCrypto.RAND_SEED_LENGTH_IN_BYTES;
final SecureRandom secureRandom = sslParameters.getSecureRandomMember();
if (secureRandom == null) {
NativeCrypto.RAND_load_file("/dev/urandom", seedLengthInBytes);
} else {
NativeCrypto.RAND_seed(secureRandom.generateSeed(seedLengthInBytes));
}
final boolean client = sslParameters.getUseClientMode();
final int sslCtxNativePointer = (client) ? sslParameters.getClientSessionContext().sslCtxNativePointer : sslParameters.getServerSessionContext().sslCtxNativePointer;
this.sslNativePointer = 0;
boolean exception = true;
try {
sslNativePointer = NativeCrypto.SSL_new(sslCtxNativePointer);
guard.open("close");
// clients will receive a call back to request certificates.
if (!client) {
Set<String> keyTypes = new HashSet<String>();
for (String enabledCipherSuite : enabledCipherSuites) {
if (enabledCipherSuite.equals(NativeCrypto.TLS_EMPTY_RENEGOTIATION_INFO_SCSV)) {
continue;
}
String keyType = CipherSuite.getByName(enabledCipherSuite).getServerKeyType();
if (keyType != null) {
keyTypes.add(keyType);
}
}
for (String keyType : keyTypes) {
try {
setCertificate(sslParameters.getKeyManager().chooseServerAlias(keyType, null, this));
} catch (CertificateEncodingException e) {
throw new IOException(e);
}
}
}
NativeCrypto.setEnabledProtocols(sslNativePointer, enabledProtocols);
NativeCrypto.setEnabledCipherSuites(sslNativePointer, enabledCipherSuites);
if (enabledCompressionMethods.length != 0) {
NativeCrypto.setEnabledCompressionMethods(sslNativePointer, enabledCompressionMethods);
}
if (useSessionTickets) {
NativeCrypto.SSL_clear_options(sslNativePointer, NativeCrypto.SSL_OP_NO_TICKET);
}
if (hostname != null) {
NativeCrypto.SSL_set_tlsext_host_name(sslNativePointer, hostname);
}
boolean enableSessionCreation = sslParameters.getEnableSessionCreation();
if (!enableSessionCreation) {
NativeCrypto.SSL_set_session_creation_enabled(sslNativePointer, enableSessionCreation);
}
AbstractSessionContext sessionContext;
if (client) {
// look for client session to reuse
ClientSessionContext clientSessionContext = sslParameters.getClientSessionContext();
sessionContext = clientSessionContext;
OpenSSLSessionImpl session = getCachedClientSession(clientSessionContext);
if (session != null) {
NativeCrypto.SSL_set_session(sslNativePointer, session.sslSessionNativePointer);
}
} else {
sessionContext = sslParameters.getServerSessionContext();
}
// setup peer certificate verification
if (client) {
// TODO support for anonymous cipher would require us to
// conditionally use SSL_VERIFY_NONE
} else {
// needing client auth takes priority...
boolean certRequested;
if (sslParameters.getNeedClientAuth()) {
NativeCrypto.SSL_set_verify(sslNativePointer, NativeCrypto.SSL_VERIFY_PEER | NativeCrypto.SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
certRequested = true;
// ... over just wanting it...
} else if (sslParameters.getWantClientAuth()) {
NativeCrypto.SSL_set_verify(sslNativePointer, NativeCrypto.SSL_VERIFY_PEER);
certRequested = true;
// ... and it defaults properly so don't call SSL_set_verify in the common case.
} else {
certRequested = false;
}
if (certRequested) {
X509TrustManager trustManager = sslParameters.getTrustManager();
X509Certificate[] issuers = trustManager.getAcceptedIssuers();
if (issuers != null && issuers.length != 0) {
byte[][] issuersBytes;
try {
issuersBytes = NativeCrypto.encodeIssuerX509Principals(issuers);
} catch (CertificateEncodingException e) {
throw new IOException("Problem encoding principals", e);
}
NativeCrypto.SSL_set_client_CA_list(sslNativePointer, issuersBytes);
}
}
}
if (client && full) {
// we want to do a full synchronous handshake, so turn off cutthrough
NativeCrypto.SSL_clear_mode(sslNativePointer, NativeCrypto.SSL_MODE_HANDSHAKE_CUTTHROUGH);
}
// Temporarily use a different timeout for the handshake process
int savedTimeoutMilliseconds = getSoTimeout();
if (handshakeTimeoutMilliseconds >= 0) {
setSoTimeout(handshakeTimeoutMilliseconds);
}
int sslSessionNativePointer;
try {
sslSessionNativePointer = NativeCrypto.SSL_do_handshake(sslNativePointer, socket.getFileDescriptor$(), this, getSoTimeout(), client);
} catch (CertificateException e) {
SSLHandshakeException wrapper = new SSLHandshakeException(e.getMessage());
wrapper.initCause(e);
throw wrapper;
}
byte[] sessionId = NativeCrypto.SSL_SESSION_session_id(sslSessionNativePointer);
sslSession = (OpenSSLSessionImpl) sessionContext.getSession(sessionId);
if (sslSession != null) {
sslSession.lastAccessedTime = System.currentTimeMillis();
NativeCrypto.SSL_SESSION_free(sslSessionNativePointer);
} else {
if (!enableSessionCreation) {
// Should have been prevented by NativeCrypto.SSL_set_session_creation_enabled
throw new IllegalStateException("SSL Session may not be created");
}
X509Certificate[] localCertificates = createCertChain(NativeCrypto.SSL_get_certificate(sslNativePointer));
X509Certificate[] peerCertificates = createCertChain(NativeCrypto.SSL_get_peer_cert_chain(sslNativePointer));
if (wrappedHost == null) {
sslSession = new OpenSSLSessionImpl(sslSessionNativePointer, localCertificates, peerCertificates, super.getInetAddress().getHostName(), super.getPort(), sessionContext);
} else {
sslSession = new OpenSSLSessionImpl(sslSessionNativePointer, localCertificates, peerCertificates, wrappedHost, wrappedPort, sessionContext);
}
// if not, putSession later in handshakeCompleted() callback
if (handshakeCompleted) {
sessionContext.putSession(sslSession);
}
}
// Restore the original timeout now that the handshake is complete
if (handshakeTimeoutMilliseconds >= 0) {
setSoTimeout(savedTimeoutMilliseconds);
}
// if not, notifyHandshakeCompletedListeners later in handshakeCompleted() callback
if (handshakeCompleted) {
notifyHandshakeCompletedListeners();
}
exception = false;
} catch (SSLProtocolException e) {
throw new SSLHandshakeException(e);
} finally {
// on exceptional exit, treat the socket as closed
if (exception) {
close();
}
}
}
use of java.security.SecureRandom in project pulsar by yahoo.
the class SecurityUtility method createSslContext.
public static SSLContext createSslContext(boolean allowInsecureConnection, Certificate[] trustCertficates, Certificate[] certificates, PrivateKey privateKey) throws GeneralSecurityException {
KeyStoreHolder ksh = new KeyStoreHolder();
TrustManager[] trustManagers = null;
KeyManager[] keyManagers = null;
// Set trusted certificate
if (allowInsecureConnection) {
trustManagers = InsecureTrustManagerFactory.INSTANCE.getTrustManagers();
} else {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
if (trustCertficates == null || trustCertficates.length == 0) {
tmf.init((KeyStore) null);
} else {
ksh.setCertificate("trust", trustCertficates[0]);
tmf.init(ksh.getKeyStore());
}
trustManagers = tmf.getTrustManagers();
}
// Set private key and certificate
if (certificates != null && privateKey != null) {
ksh.setPrivateKey("private", privateKey, certificates);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ksh.getKeyStore(), "".toCharArray());
keyManagers = kmf.getKeyManagers();
}
SSLContext sslCtx = SSLContext.getInstance("TLS");
sslCtx.init(keyManagers, trustManagers, new SecureRandom());
return sslCtx;
}
use of java.security.SecureRandom in project cassandra by apache.
the class CipherFactoryTest method setup.
@Before
public void setup() {
secureRandom = new SecureRandom(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
encryptionOptions = EncryptionContextGenerator.createEncryptionOptions();
cipherFactory = new CipherFactory(encryptionOptions);
}
use of java.security.SecureRandom in project cordova-android by apache.
the class CordovaBridge method generateBridgeSecret.
/** Called by cordova.js to initialize the bridge. */
int generateBridgeSecret() {
SecureRandom randGen = new SecureRandom();
expectedBridgeSecret = randGen.nextInt(Integer.MAX_VALUE);
return expectedBridgeSecret;
}
use of java.security.SecureRandom in project hadoop by apache.
the class TestCryptoCodec method testCalculateIV.
/**
* Regression test for IV calculation, see HADOOP-11343
*/
@Test(timeout = 120000)
public void testCalculateIV() throws Exception {
JceAesCtrCryptoCodec codec = new JceAesCtrCryptoCodec();
codec.setConf(conf);
SecureRandom sr = new SecureRandom();
byte[] initIV = new byte[16];
byte[] IV = new byte[16];
long iterations = 1000;
long counter = 10000;
// Overflow test, IV: 00 00 00 00 00 00 00 00 ff ff ff ff ff ff ff ff
for (int i = 0; i < 8; i++) {
initIV[8 + i] = (byte) 0xff;
}
for (long j = 0; j < counter; j++) {
assertIVCalculation(codec, initIV, j, IV);
}
// Random IV and counter sequence test
for (long i = 0; i < iterations; i++) {
sr.nextBytes(initIV);
for (long j = 0; j < counter; j++) {
assertIVCalculation(codec, initIV, j, IV);
}
}
// Random IV and random counter test
for (long i = 0; i < iterations; i++) {
sr.nextBytes(initIV);
for (long j = 0; j < counter; j++) {
long c = sr.nextLong();
assertIVCalculation(codec, initIV, c, IV);
}
}
}
Aggregations