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);
});
}
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());
}
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);
});
}
}
}
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);
}
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);
}
Aggregations