Search in sources :

Example 46 with Cipher

use of javax.crypto.Cipher in project jdk8u_jdk by JetBrains.

the class CheckCipherSuites method main.

public static void main(String[] args) throws Exception {
    long start = System.currentTimeMillis();
    String[] ENABLED;
    String[] SUPPORTED;
    try {
        Cipher c = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec key = new SecretKeySpec(new byte[32], "AES");
        c.init(Cipher.ENCRYPT_MODE, key);
        System.out.println("AES/256 is available");
        ENABLED = ENABLED_UNLIMITED;
        SUPPORTED = SUPPORTED_UNLIMITED;
    } catch (Exception e) {
        System.out.println("AES/256 is NOT available (" + e + ")");
        ENABLED = ENABLED_DEFAULT;
        SUPPORTED = SUPPORTED_DEFAULT;
    }
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket socket = (SSLSocket) factory.createSocket();
    String[] enabled = socket.getEnabledCipherSuites();
    System.out.println("Default enabled ciphersuites:");
    showSuites(enabled);
    if (Arrays.equals(ENABLED, enabled) == false) {
        System.out.println("*** MISMATCH, should be ***");
        showSuites(ENABLED);
        throw new Exception("Enabled ciphersuite mismatch");
    }
    System.out.println("OK");
    System.out.println();
    String[] supported = socket.getSupportedCipherSuites();
    System.out.println("Supported ciphersuites:");
    showSuites(supported);
    if (Arrays.equals(SUPPORTED, supported) == false) {
        System.out.println("*** MISMATCH, should be ***");
        showSuites(SUPPORTED);
        throw new Exception("Supported ciphersuite mismatch");
    }
    System.out.println("OK");
    long end = System.currentTimeMillis();
    System.out.println("Done (" + (end - start) + " ms).");
}
Also used : Cipher(javax.crypto.Cipher)

Example 47 with Cipher

use of javax.crypto.Cipher in project kdeconnect-android by KDE.

the class RsaHelper method encrypt.

public static NetworkPackage encrypt(NetworkPackage np, PublicKey publicKey) throws GeneralSecurityException, JSONException {
    String serialized = np.serialize();
    int chunkSize = 128;
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    JSONArray chunks = new JSONArray();
    while (serialized.length() > 0) {
        if (serialized.length() < chunkSize) {
            chunkSize = serialized.length();
        }
        String chunk = serialized.substring(0, chunkSize);
        serialized = serialized.substring(chunkSize);
        byte[] chunkBytes = chunk.getBytes(Charset.defaultCharset());
        byte[] encryptedChunk;
        encryptedChunk = cipher.doFinal(chunkBytes);
        chunks.put(Base64.encodeToString(encryptedChunk, Base64.NO_WRAP));
    }
    //Log.i("NetworkPackage", "Encrypted " + chunks.length()+" chunks");
    NetworkPackage encrypted = new NetworkPackage(NetworkPackage.PACKAGE_TYPE_ENCRYPTED);
    encrypted.set("data", chunks);
    encrypted.setPayload(np.getPayload(), np.getPayloadSize());
    return encrypted;
}
Also used : JSONArray(org.json.JSONArray) NetworkPackage(org.kde.kdeconnect.NetworkPackage) Cipher(javax.crypto.Cipher)

Example 48 with Cipher

use of javax.crypto.Cipher in project kdeconnect-android by KDE.

the class RsaHelper method decrypt.

public static NetworkPackage decrypt(NetworkPackage np, PrivateKey privateKey) throws GeneralSecurityException, JSONException {
    JSONArray chunks = np.getJSONArray("data");
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    String decryptedJson = "";
    for (int i = 0; i < chunks.length(); i++) {
        byte[] encryptedChunk = Base64.decode(chunks.getString(i), Base64.NO_WRAP);
        String decryptedChunk = new String(cipher.doFinal(encryptedChunk));
        decryptedJson += decryptedChunk;
    }
    NetworkPackage decrypted = NetworkPackage.unserialize(decryptedJson);
    decrypted.setPayload(np.getPayload(), np.getPayloadSize());
    return decrypted;
}
Also used : JSONArray(org.json.JSONArray) NetworkPackage(org.kde.kdeconnect.NetworkPackage) Cipher(javax.crypto.Cipher)

Example 49 with Cipher

use of javax.crypto.Cipher in project jdk8u_jdk by JetBrains.

the class TestCipherPBE method runTest.

private void runTest(String algorithm) throws InvalidKeySpecException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, ShortBufferException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
    out.println("=> Testing: " + algorithm);
    try {
        // Initialization
        AlgorithmParameterSpec algoParamSpec = new PBEParameterSpec(SALT, 6);
        SecretKey secretKey = SecretKeyFactory.getInstance(KEY_ALGO).generateSecret(new PBEKeySpec(("Secret Key Value").toCharArray()));
        Cipher ci = Cipher.getInstance(algorithm);
        ci.init(Cipher.ENCRYPT_MODE, secretKey, algoParamSpec);
        // Encryption
        byte[] cipherText = ci.doFinal(PLAIN_TEXT);
        // Decryption
        ci.init(Cipher.DECRYPT_MODE, secretKey, algoParamSpec);
        byte[] recoveredText = ci.doFinal(cipherText);
        if (algorithm.contains("TripleDES")) {
            throw new RuntimeException("Expected InvalidKeyException exception uncaugh");
        }
        // Comparison
        if (!Arrays.equals(PLAIN_TEXT, recoveredText)) {
            throw new RuntimeException("Test failed: plainText is not equal to recoveredText");
        }
        out.println("Test Passed.");
    } catch (InvalidKeyException ex) {
        if (algorithm.contains("TripleDES")) {
            out.println("Expected InvalidKeyException raised");
        } else {
            throw new RuntimeException(ex);
        }
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) Cipher(javax.crypto.Cipher) InvalidKeyException(java.security.InvalidKeyException) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec)

Example 50 with Cipher

use of javax.crypto.Cipher in project jdk8u_jdk by JetBrains.

the class CipherInputStreamExceptions method gcm_AEADBadTag.

/* Full read stream, check that getMoreData() is throwing an exception
     * This test
     *   1) Encrypt 100 bytes with AES/GCM/PKCS5Padding
     *   2) Changes the last byte to invalidate the authetication tag.
     *   3) Fully reads CipherInputStream to decrypt the message and closes
     */
static void gcm_AEADBadTag() throws Exception {
    Cipher c;
    byte[] read = new byte[200];
    System.out.println("Running gcm_AEADBadTag");
    // Encrypt 100 bytes with AES/GCM/PKCS5Padding
    byte[] ct = encryptedText("GCM", 100);
    // Corrupt the encrypted message
    ct = corruptGCM(ct);
    // Create stream for decryption
    CipherInputStream in = getStream("GCM", ct);
    try {
        int size = in.read(read);
        throw new RuntimeException("Fail: CipherInputStream.read() " + "returned " + size + " and didn't throw an exception.");
    } catch (IOException e) {
        Throwable ec = e.getCause();
        if (ec instanceof AEADBadTagException) {
            System.out.println("  Pass.");
        } else {
            System.out.println("  Fail: " + ec.getMessage());
            throw new RuntimeException(ec);
        }
    } finally {
        in.close();
    }
}
Also used : RuntimeException(java.lang.RuntimeException) CipherInputStream(javax.crypto.CipherInputStream) Throwable(java.lang.Throwable) Cipher(javax.crypto.Cipher) IOException(java.io.IOException) AEADBadTagException(javax.crypto.AEADBadTagException)

Aggregations

Cipher (javax.crypto.Cipher)1531 SecretKeySpec (javax.crypto.spec.SecretKeySpec)516 SecretKey (javax.crypto.SecretKey)377 IvParameterSpec (javax.crypto.spec.IvParameterSpec)368 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)349 InvalidKeyException (java.security.InvalidKeyException)257 IOException (java.io.IOException)202 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)202 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)196 BadPaddingException (javax.crypto.BadPaddingException)183 GeneralSecurityException (java.security.GeneralSecurityException)161 SecretKeyFactory (javax.crypto.SecretKeyFactory)149 Key (java.security.Key)148 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)134 SecureRandom (java.security.SecureRandom)105 PrivateKey (java.security.PrivateKey)93 PublicKey (java.security.PublicKey)86 UnsupportedEncodingException (java.io.UnsupportedEncodingException)84 PBEKeySpec (javax.crypto.spec.PBEKeySpec)82 KeyGenerator (javax.crypto.KeyGenerator)78