Skip to content

Instantly share code, notes, and snippets.

@p-
Created May 14, 2019 11:19
Show Gist options
  • Save p-/a63fb8740dfdb72d8d1395b60b525de5 to your computer and use it in GitHub Desktop.
Save p-/a63fb8740dfdb72d8d1395b60b525de5 to your computer and use it in GitHub Desktop.
package io.hf.samples.tink.positive;
import com.google.crypto.tink.Aead;
import com.google.crypto.tink.KeysetHandle;
import com.google.crypto.tink.aead.AeadConfig;
import com.google.crypto.tink.aead.AeadFactory;
import com.google.crypto.tink.aead.AeadKeyTemplates;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class TinkPositive {
// Based on: https://github.com/google/tink/blob/1.2/docs/JAVA-HOWTO.md
// using 'com.google.crypto.tink:tink:1.2.2'
public final static void main(String[] args) throws Exception {
// 1. Use only AEAD primitive
// AEAD: Authenticated Encryption with Associated Data
AeadConfig.register();
// 2. Generate the key material
KeysetHandle keysetHandle = KeysetHandle.generateNew(AeadKeyTemplates.AES256_GCM);
// 3. Get the primitive.
Aead aead = AeadFactory.getPrimitive(keysetHandle);
String plainText = "Tink Positive!";
System.out.println("PlainText: " + plainText);
// 4. Use the primitive to encrypt a plaintext.
byte[] cipherText = aead.encrypt(plainText.getBytes(StandardCharsets.UTF_8), null);
String base64 = new String(Base64.getEncoder().encode(cipherText), StandardCharsets.UTF_8);
System.out.println("Encrypted: " + base64);
// 5. decrypt a ciphertext.
byte[] decrypted = aead.decrypt(cipherText, null);
String decryptedText = new String(decrypted, StandardCharsets.UTF_8);
System.out.println("Decrypted: " + decryptedText);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment