Search in sources :

Example 51 with Aead

use of com.google.crypto.tink.Aead in project tink by google.

the class ChaCha20Poly1305Test method testNullPlaintextOrCiphertext.

@Test
public void testNullPlaintextOrCiphertext() throws Exception {
    Assume.assumeFalse(TinkFips.useOnlyFips());
    Aead aead = createInstance(Random.randBytes(KEY_SIZE));
    byte[] aad = new byte[] { 1, 2, 3 };
    assertThrows(NullPointerException.class, () -> {
        byte[] unused = aead.encrypt(null, aad);
    });
    assertThrows(NullPointerException.class, () -> {
        byte[] unused = aead.encrypt(null, null);
    });
    assertThrows(NullPointerException.class, () -> {
        byte[] unused = aead.decrypt(null, aad);
    });
    assertThrows(NullPointerException.class, () -> {
        byte[] unused = aead.decrypt(null, null);
    });
}
Also used : Aead(com.google.crypto.tink.Aead) Test(org.junit.Test)

Example 52 with Aead

use of com.google.crypto.tink.Aead in project tink by google.

the class ChaCha20Poly1305Test method testRandomNonce.

/**
 * This is a very simple test for the randomness of the nonce. The test simply checks that the
 * multiple ciphertexts of the same message are distinct.
 */
@Test
public void testRandomNonce() throws Exception {
    Assume.assumeFalse(TinkFips.useOnlyFips());
    byte[] key = Random.randBytes(KEY_SIZE);
    Aead aead = createInstance(key);
    byte[] message = new byte[0];
    byte[] aad = new byte[0];
    HashSet<String> ciphertexts = new HashSet<String>();
    final int samples = 1 << 10;
    for (int i = 0; i < samples; i++) {
        byte[] ct = aead.encrypt(message, aad);
        String ctHex = TestUtil.hexEncode(ct);
        assertFalse(ciphertexts.contains(ctHex));
        ciphertexts.add(ctHex);
    }
    assertEquals(samples, ciphertexts.size());
}
Also used : Aead(com.google.crypto.tink.Aead) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 53 with Aead

use of com.google.crypto.tink.Aead in project tink by google.

the class ChaCha20Poly1305Test method testModifyCiphertext.

@Test
public void testModifyCiphertext() throws Exception {
    Assume.assumeFalse(TinkFips.useOnlyFips());
    byte[] key = Random.randBytes(KEY_SIZE);
    Aead aead = createInstance(key);
    byte[] aad = Random.randBytes(16);
    byte[] message = Random.randBytes(32);
    byte[] ciphertext = aead.encrypt(message, aad);
    for (BytesMutation mutation : TestUtil.generateMutations(ciphertext)) {
        assertThrows(String.format("Decrypting modified ciphertext should fail : ciphertext = %s, aad = %s," + " description = %s", Hex.encode(mutation.value), Arrays.toString(aad), mutation.description), GeneralSecurityException.class, () -> {
            byte[] unused = aead.decrypt(mutation.value, aad);
        });
    }
    // Modify AAD
    for (int b = 0; b < aad.length; b++) {
        for (int bit = 0; bit < 8; bit++) {
            byte[] modified = Arrays.copyOf(aad, aad.length);
            modified[b] ^= (byte) (1 << bit);
            assertThrows(AEADBadTagException.class, () -> {
                byte[] unused = aead.decrypt(ciphertext, modified);
            });
        }
    }
}
Also used : Aead(com.google.crypto.tink.Aead) BytesMutation(com.google.crypto.tink.testing.TestUtil.BytesMutation) Test(org.junit.Test)

Example 54 with Aead

use of com.google.crypto.tink.Aead in project tink by google.

the class CleartextKeysetExample method main.

public static void main(String[] args) throws Exception {
    if (args.length != 2 && args.length != 4) {
        System.err.printf("Expected 2 or 4 parameters, got %d\n", args.length);
        System.err.println("Usage: java CleartextKeysetExample generate/encrypt/decrypt key-file input-file" + " output-file");
        System.exit(1);
    }
    String mode = args[0];
    if (!MODE_ENCRYPT.equals(mode) && !MODE_DECRYPT.equals(mode) && !MODE_GENERATE.equals(mode)) {
        System.err.print("The first argument should be either encrypt, decrypt or generate");
        System.exit(1);
    }
    File keyFile = new File(args[1]);
    // Initialise Tink: register all AEAD key types with the Tink runtime
    AeadConfig.register();
    if (MODE_GENERATE.equals(mode)) {
        // [START generate-a-new-keyset]
        KeysetHandle handle = KeysetHandle.generateNew(KeyTemplates.get("AES128_GCM"));
        // [END generate-a-new-keyset]
        // [START store-a-cleartext-keyset]
        CleartextKeysetHandle.write(handle, JsonKeysetWriter.withFile(keyFile));
        // [END store-a-cleartext-keyset]
        System.exit(0);
    }
    // Use the primitive to encrypt/decrypt files
    // Read the cleartext keyset
    KeysetHandle handle = null;
    try {
        handle = CleartextKeysetHandle.read(JsonKeysetReader.withFile(keyFile));
    } catch (GeneralSecurityException | IOException ex) {
        System.err.println("Error reading key: " + ex);
        System.exit(1);
    }
    // Get the primitive
    Aead aead = null;
    try {
        aead = handle.getPrimitive(Aead.class);
    } catch (GeneralSecurityException ex) {
        System.err.println("Error creating primitive: %s " + ex);
        System.exit(1);
    }
    byte[] input = Files.readAllBytes(Paths.get(args[2]));
    File outputFile = new File(args[3]);
    if (MODE_ENCRYPT.equals(mode)) {
        byte[] ciphertext = aead.encrypt(input, EMPTY_ASSOCIATED_DATA);
        try (FileOutputStream stream = new FileOutputStream(outputFile)) {
            stream.write(ciphertext);
        }
    } else if (MODE_DECRYPT.equals(mode)) {
        byte[] plaintext = aead.decrypt(input, EMPTY_ASSOCIATED_DATA);
        try (FileOutputStream stream = new FileOutputStream(outputFile)) {
            stream.write(plaintext);
        }
    }
    System.exit(0);
}
Also used : CleartextKeysetHandle(com.google.crypto.tink.CleartextKeysetHandle) KeysetHandle(com.google.crypto.tink.KeysetHandle) GeneralSecurityException(java.security.GeneralSecurityException) FileOutputStream(java.io.FileOutputStream) Aead(com.google.crypto.tink.Aead) IOException(java.io.IOException) File(java.io.File)

Example 55 with Aead

use of com.google.crypto.tink.Aead in project tink by google.

the class GcsEnvelopeAeadExample method main.

public static void main(String[] args) throws Exception {
    if (args.length != 6) {
        System.err.printf("Expected 6 parameters, got %d\n", args.length);
        System.err.println("Usage: java GcsEnvelopeAeadExample encrypt/decrypt kek-uri gcp-credential-file" + " gcp-project-id input-file output-file");
        System.exit(1);
    }
    String mode = args[0];
    String kekUri = args[1];
    String gcpCredentialFilename = args[2];
    String gcpProjectId = args[3];
    // Initialise Tink: register all AEAD key types with the Tink runtime
    AeadConfig.register();
    // Read the GCP credentials and set up client
    try {
        GcpKmsClient.register(Optional.of(kekUri), Optional.of(gcpCredentialFilename));
    } catch (GeneralSecurityException ex) {
        System.err.println("Error initializing GCP client: " + ex);
        System.exit(1);
    }
    // Create envelope AEAD primitive using AES256 GCM for encrypting the data
    Aead aead = null;
    try {
        KeysetHandle handle = KeysetHandle.generateNew(KmsEnvelopeAeadKeyManager.createKeyTemplate(kekUri, KeyTemplates.get("AES256_GCM")));
        aead = handle.getPrimitive(Aead.class);
    } catch (GeneralSecurityException ex) {
        System.err.println("Error creating primitive: %s " + ex);
        System.exit(1);
    }
    GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(gcpCredentialFilename)).createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
    Storage storage = StorageOptions.newBuilder().setProjectId(gcpProjectId).setCredentials(credentials).build().getService();
    // Use the primitive to encrypt/decrypt files.
    if (MODE_ENCRYPT.equals(mode)) {
        // Encrypt the local file
        byte[] input = Files.readAllBytes(Paths.get(args[4]));
        String gcsBlobPath = args[5];
        // This will bind the encryption to the location of the GCS blob. That if, if you rename or
        // move the blob to a different bucket, decryption will fail.
        // See https://developers.google.com/tink/aead#associated_data.
        byte[] associatedData = gcsBlobPath.getBytes(UTF_8);
        byte[] ciphertext = aead.encrypt(input, associatedData);
        // Upload to GCS
        String bucketName = getBucketName(gcsBlobPath);
        String objectName = getObjectName(gcsBlobPath);
        BlobId blobId = BlobId.of(bucketName, objectName);
        BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
        storage.create(blobInfo, ciphertext);
    } else if (MODE_DECRYPT.equals(mode)) {
        // Download the GCS blob
        String gcsBlobPath = args[4];
        String bucketName = getBucketName(gcsBlobPath);
        String objectName = getObjectName(gcsBlobPath);
        byte[] input = storage.readAllBytes(bucketName, objectName);
        // Decrypt to a local file
        byte[] associatedData = gcsBlobPath.getBytes(UTF_8);
        byte[] plaintext = aead.decrypt(input, associatedData);
        File outputFile = new File(args[5]);
        try (FileOutputStream stream = new FileOutputStream(outputFile)) {
            stream.write(plaintext);
        }
    } else {
        System.err.println("The first argument must be either encrypt or decrypt, got: " + mode);
        System.exit(1);
    }
    System.exit(0);
}
Also used : KeysetHandle(com.google.crypto.tink.KeysetHandle) Storage(com.google.cloud.storage.Storage) GeneralSecurityException(java.security.GeneralSecurityException) FileOutputStream(java.io.FileOutputStream) Aead(com.google.crypto.tink.Aead) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) BlobInfo(com.google.cloud.storage.BlobInfo) BlobId(com.google.cloud.storage.BlobId) File(java.io.File) FileInputStream(java.io.FileInputStream)

Aggregations

Aead (com.google.crypto.tink.Aead)84 Test (org.junit.Test)67 GeneralSecurityException (java.security.GeneralSecurityException)25 KeysetHandle (com.google.crypto.tink.KeysetHandle)21 Key (com.google.crypto.tink.proto.Keyset.Key)9 CleartextKeysetHandle (com.google.crypto.tink.CleartextKeysetHandle)7 IOException (java.io.IOException)7 EncryptRequest (com.amazonaws.services.kms.model.EncryptRequest)6 KeyTemplate (com.google.crypto.tink.KeyTemplate)6 ByteString (com.google.protobuf.ByteString)6 DecryptRequest (com.amazonaws.services.kms.model.DecryptRequest)5 EncryptResult (com.amazonaws.services.kms.model.EncryptResult)5 KmsEnvelopeAeadKey (com.google.crypto.tink.proto.KmsEnvelopeAeadKey)5 File (java.io.File)5 FileOutputStream (java.io.FileOutputStream)5 DecryptResult (com.amazonaws.services.kms.model.DecryptResult)4 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)4 ByteBuffer (java.nio.ByteBuffer)4 AesEaxKey (com.google.crypto.tink.proto.AesEaxKey)3 AesGcmKey (com.google.crypto.tink.proto.AesGcmKey)3