Search in sources :

Example 56 with Aead

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

the class EnvelopeAeadExample method main.

public static void main(String[] args) throws Exception {
    if (args.length != 5 && args.length != 6) {
        System.err.printf("Expected 5 or 6 parameters, got %d\n", args.length);
        System.err.println("Usage: java EnvelopeAeadExample encrypt/decrypt kek-uri gcp-credential-file" + " input-file output-file [associated-data]");
        System.exit(1);
    }
    String mode = args[0];
    String kekUri = args[1];
    String gcpCredentialFilename = args[2];
    byte[] input = Files.readAllBytes(Paths.get(args[3]));
    File outputFile = new File(args[4]);
    byte[] associatedData = new byte[0];
    if (args.length == 6) {
        System.out.println("Associated data!");
        associatedData = args[5].getBytes(UTF_8);
    }
    // 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);
    }
    // Use the primitive to encrypt/decrypt files.
    if (MODE_ENCRYPT.equals(mode)) {
        byte[] ciphertext = aead.encrypt(input, associatedData);
        try (FileOutputStream stream = new FileOutputStream(outputFile)) {
            stream.write(ciphertext);
        }
    } else if (MODE_DECRYPT.equals(mode)) {
        byte[] plaintext = aead.decrypt(input, associatedData);
        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) GeneralSecurityException(java.security.GeneralSecurityException) FileOutputStream(java.io.FileOutputStream) Aead(com.google.crypto.tink.Aead) File(java.io.File)

Example 57 with Aead

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

the class AeadServiceImpl method decrypt.

/**
 * Decrypts a message.
 */
@Override
public void decrypt(AeadDecryptRequest request, StreamObserver<AeadDecryptResponse> responseObserver) {
    AeadDecryptResponse response;
    try {
        KeysetHandle keysetHandle = CleartextKeysetHandle.read(BinaryKeysetReader.withBytes(request.getKeyset().toByteArray()));
        Aead aead = keysetHandle.getPrimitive(Aead.class);
        byte[] plaintext = aead.decrypt(request.getCiphertext().toByteArray(), request.getAssociatedData().toByteArray());
        response = AeadDecryptResponse.newBuilder().setPlaintext(ByteString.copyFrom(plaintext)).build();
    } catch (GeneralSecurityException | InvalidProtocolBufferException e) {
        response = AeadDecryptResponse.newBuilder().setErr(e.toString()).build();
    } catch (IOException e) {
        responseObserver.onError(Status.UNKNOWN.withDescription(e.getMessage()).asException());
        return;
    }
    responseObserver.onNext(response);
    responseObserver.onCompleted();
}
Also used : CleartextKeysetHandle(com.google.crypto.tink.CleartextKeysetHandle) KeysetHandle(com.google.crypto.tink.KeysetHandle) AeadDecryptResponse(com.google.crypto.tink.proto.testing.AeadDecryptResponse) GeneralSecurityException(java.security.GeneralSecurityException) Aead(com.google.crypto.tink.Aead) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) IOException(java.io.IOException)

Example 58 with Aead

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

the class KeysetServiceImpl method writeEncrypted.

@Override
public void writeEncrypted(KeysetWriteEncryptedRequest request, StreamObserver<KeysetWriteEncryptedResponse> responseObserver) {
    KeysetWriteEncryptedResponse response;
    try {
        // get masterAead
        KeysetHandle masterKeysetHandle = CleartextKeysetHandle.read(BinaryKeysetReader.withBytes(request.getMasterKeyset().toByteArray()));
        Aead masterAead = masterKeysetHandle.getPrimitive(Aead.class);
        // get keysetHandle
        KeysetHandle keysetHandle = CleartextKeysetHandle.read(BinaryKeysetReader.withBytes(request.getKeyset().toByteArray()));
        // write keysetHandle as encrypted keyset
        ByteArrayOutputStream keysetStream = new ByteArrayOutputStream();
        KeysetWriter writer = BinaryKeysetWriter.withOutputStream(keysetStream);
        if (request.hasAssociatedData()) {
            keysetHandle.writeWithAssociatedData(writer, masterAead, request.getAssociatedData().getValue().toByteArray());
        } else {
            keysetHandle.write(writer, masterAead);
        }
        keysetStream.close();
        response = KeysetWriteEncryptedResponse.newBuilder().setEncryptedKeyset(ByteString.copyFrom(keysetStream.toByteArray())).build();
    } catch (GeneralSecurityException | InvalidProtocolBufferException e) {
        response = KeysetWriteEncryptedResponse.newBuilder().setErr(e.toString()).build();
    } catch (IOException e) {
        responseObserver.onError(Status.UNKNOWN.withDescription(e.getMessage()).asException());
        return;
    }
    responseObserver.onNext(response);
    responseObserver.onCompleted();
}
Also used : KeysetHandle(com.google.crypto.tink.KeysetHandle) CleartextKeysetHandle(com.google.crypto.tink.CleartextKeysetHandle) KeysetWriteEncryptedResponse(com.google.crypto.tink.proto.testing.KeysetWriteEncryptedResponse) JsonKeysetWriter(com.google.crypto.tink.JsonKeysetWriter) BinaryKeysetWriter(com.google.crypto.tink.BinaryKeysetWriter) KeysetWriter(com.google.crypto.tink.KeysetWriter) GeneralSecurityException(java.security.GeneralSecurityException) Aead(com.google.crypto.tink.Aead) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Example 59 with Aead

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

the class EncryptThenAuthenticateTest method testNullPlaintextOrCiphertext.

@Test
public void testNullPlaintextOrCiphertext() throws Exception {
    Aead aead = getAead(Random.randBytes(16), Random.randBytes(16), 16, 16, "HMACSHA256");
    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 60 with Aead

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

the class EncryptThenAuthenticateTest method testEmptyAssociatedData.

@Test
public void testEmptyAssociatedData() throws Exception {
    Aead aead = getAead(Random.randBytes(16), Random.randBytes(16), 16, 16, "HMACSHA256");
    byte[] aad = new byte[0];
    byte[] plaintext = Random.randBytes(1001);
    {
        // encrypting with aad as a 0-length array
        byte[] ciphertext = aead.encrypt(plaintext, aad);
        byte[] decrypted = aead.decrypt(ciphertext, aad);
        assertArrayEquals(plaintext, decrypted);
        byte[] decrypted2 = aead.decrypt(ciphertext, null);
        assertArrayEquals(plaintext, decrypted2);
        byte[] badAad = new byte[] { 1, 2, 3 };
        assertThrows(GeneralSecurityException.class, () -> {
            byte[] unused = aead.decrypt(ciphertext, badAad);
        });
    }
    {
        // encrypting with aad equal to null
        byte[] ciphertext = aead.encrypt(plaintext, null);
        byte[] decrypted = aead.decrypt(ciphertext, aad);
        assertArrayEquals(plaintext, decrypted);
        byte[] decrypted2 = aead.decrypt(ciphertext, null);
        assertArrayEquals(plaintext, decrypted2);
        byte[] badAad = new byte[] { 1, 2, 3 };
        assertThrows(GeneralSecurityException.class, () -> {
            byte[] unused = aead.decrypt(ciphertext, badAad);
        });
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) Aead(com.google.crypto.tink.Aead) Test(org.junit.Test)

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