Search in sources :

Example 31 with SecureRandom

use of java.security.SecureRandom in project keywhiz by square.

the class GenerateAesKeyCommandTest method testKeyGeneration.

@Test
public void testKeyGeneration() throws Exception {
    char[] password = "CHANGE".toCharArray();
    Path destination = Paths.get(temporaryFolder.getRoot().getPath(), "derivation.jceks");
    int keySize = 128;
    String alias = "baseKey";
    GenerateAesKeyCommand.generate(password, destination, keySize, alias, new SecureRandom());
    assertThat(destination).exists();
    KeyStore keyStore = KeyStore.getInstance("JCEKS");
    try (InputStream in = Files.newInputStream(destination)) {
        keyStore.load(in, password);
    }
    assertThat(keyStore.isKeyEntry(alias)).isTrue();
    Key key = keyStore.getKey(alias, password);
    assertThat(key).isInstanceOf(SecretKey.class);
    SecretKey secretKey = (SecretKey) key;
    assertThat(secretKey.getEncoded()).hasSize(keySize / 8);
}
Also used : Path(java.nio.file.Path) SecretKey(javax.crypto.SecretKey) InputStream(java.io.InputStream) SecureRandom(java.security.SecureRandom) KeyStore(java.security.KeyStore) Key(java.security.Key) SecretKey(javax.crypto.SecretKey) Test(org.junit.Test)

Example 32 with SecureRandom

use of java.security.SecureRandom in project okhttp by square.

the class MockWebServer method processHandshakeFailure.

private void processHandshakeFailure(Socket raw) throws Exception {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, new TrustManager[] { UNTRUSTED_TRUST_MANAGER }, new SecureRandom());
    SSLSocketFactory sslSocketFactory = context.getSocketFactory();
    SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true);
    try {
        // we're testing a handshake failure
        socket.startHandshake();
        throw new AssertionError();
    } catch (IOException expected) {
    }
    socket.close();
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 33 with SecureRandom

use of java.security.SecureRandom in project okhttp by square.

the class MockWebServer method handleWebSocketUpgrade.

private void handleWebSocketUpgrade(Socket socket, BufferedSource source, BufferedSink sink, RecordedRequest request, MockResponse response) throws IOException {
    String key = request.getHeader("Sec-WebSocket-Key");
    response.setHeader("Sec-WebSocket-Accept", WebSocketProtocol.acceptHeader(key));
    writeHttpResponse(socket, sink, response);
    // Adapt the request and response into our Request and Response domain model.
    String scheme = request.getTlsVersion() != null ? "https" : "http";
    // Has host and port.
    String authority = request.getHeader("Host");
    final Request fancyRequest = new Request.Builder().url(scheme + "://" + authority + "/").headers(request.getHeaders()).build();
    final Response fancyResponse = new Response.Builder().code(Integer.parseInt(response.getStatus().split(" ")[1])).message(response.getStatus().split(" ", 3)[2]).headers(response.getHeaders()).request(fancyRequest).protocol(Protocol.HTTP_1_1).build();
    final CountDownLatch connectionClose = new CountDownLatch(1);
    RealWebSocket.Streams streams = new RealWebSocket.Streams(false, source, sink) {

        @Override
        public void close() {
            connectionClose.countDown();
        }
    };
    RealWebSocket webSocket = new RealWebSocket(fancyRequest, response.getWebSocketListener(), new SecureRandom());
    response.getWebSocketListener().onOpen(webSocket, fancyResponse);
    String name = "MockWebServer WebSocket " + request.getPath();
    webSocket.initReaderAndWriter(name, 0, streams);
    try {
        webSocket.loopReader();
        // Even if messages are no longer being read we need to wait for the connection close signal.
        try {
            connectionClose.await();
        } catch (InterruptedException ignored) {
        }
    } catch (IOException e) {
        webSocket.failWebSocket(e, null);
    } finally {
        closeQuietly(sink);
        closeQuietly(source);
    }
}
Also used : Response(okhttp3.Response) RealWebSocket(okhttp3.internal.ws.RealWebSocket) Request(okhttp3.Request) SecureRandom(java.security.SecureRandom) ByteString(okio.ByteString) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 34 with SecureRandom

use of java.security.SecureRandom in project camel by apache.

the class SignatureDigestMethodTest method getKeyPair.

public static KeyPair getKeyPair(String algorithm, int keylength) {
    KeyPairGenerator keyGen;
    try {
        keyGen = KeyPairGenerator.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    keyGen.initialize(keylength, new SecureRandom());
    return keyGen.generateKeyPair();
}
Also used : SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 35 with SecureRandom

use of java.security.SecureRandom in project realm-java by realm.

the class EncryptionExampleActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Generate a key
    // IMPORTANT! This is a silly way to generate a key. It is also never stored.
    // For proper key handling please consult:
    // * https://developer.android.com/training/articles/keystore.html
    // * http://nelenkov.blogspot.dk/2012/05/storing-application-secrets-in-androids.html
    byte[] key = new byte[64];
    new SecureRandom().nextBytes(key);
    RealmConfiguration realmConfiguration = new RealmConfiguration.Builder().encryptionKey(key).build();
    // Start with a clean slate every time
    Realm.deleteRealm(realmConfiguration);
    // Open the Realm with encryption enabled
    realm = Realm.getInstance(realmConfiguration);
    // Everything continues to work as normal except for that the file is encrypted on disk
    realm.executeTransaction(new Realm.Transaction() {

        @Override
        public void execute(Realm realm) {
            Person person = realm.createObject(Person.class);
            person.setName("Happy Person");
            person.setAge(14);
        }
    });
    Person person = realm.where(Person.class).findFirst();
    Log.i(TAG, String.format("Person name: %s", person.getName()));
}
Also used : RealmConfiguration(io.realm.RealmConfiguration) SecureRandom(java.security.SecureRandom) Realm(io.realm.Realm)

Aggregations

SecureRandom (java.security.SecureRandom)720 SSLContext (javax.net.ssl.SSLContext)106 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)97 IOException (java.io.IOException)87 Test (org.junit.Test)76 SecretKey (javax.crypto.SecretKey)62 X509Certificate (java.security.cert.X509Certificate)61 KeyGenerator (javax.crypto.KeyGenerator)57 TrustManager (javax.net.ssl.TrustManager)56 X509TrustManager (javax.net.ssl.X509TrustManager)47 Cipher (javax.crypto.Cipher)46 KeyPairGenerator (java.security.KeyPairGenerator)44 BigInteger (java.math.BigInteger)42 CertificateException (java.security.cert.CertificateException)40 InvalidKeyException (java.security.InvalidKeyException)35 KeyPair (java.security.KeyPair)34 KeyStore (java.security.KeyStore)34 SecretKeySpec (javax.crypto.spec.SecretKeySpec)30 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)28 KeyManagementException (java.security.KeyManagementException)28