1

I am trying to encrypt a string and using the Google's Tink library. When I call the method encrypt and the encrypted string returns something like \<Ï~ß¾Ò0ÑP[oxRæ±E*;ÑRÂÉD«Øô§½:î. I tried Base64.DEFAULT, UTF-8 ISO-8859-1, US-ASCI and even StandarCharset.UTF_8 and similar charsets but nothing works. Please help, here is the snippet.

...
KeysetHandle keysetHandle = KeysetHandle.generateNew(AeadKeyTemplates.AES256_GCM);
Aead aead = AeadFactory.getPrimitive(keysetHandle);
byte [] str1 = str.getBytes("UTF-8");
...
byte [] output = aead.encrypt(str1, str2);
String outputStr = new String(output, "UTF-8");
...
chuckx
  • 6,484
  • 1
  • 22
  • 23
  • Well, what is it you would expect? Converting a random byte-array (as e.g. the reasult of most encryption-algorithms) to a string won't make sense in most cases.... – piet.t Jun 05 '18 at 06:24
  • 2
    The result of encryption is binary data. You can't convert that to a string using a character encoding. If you want to transport it as text, you need to use something that is meant for binary data, such as hexadecimal output, or base64 output. But you must first ask yourself whether you need to transport it as text - why not transport it as binary data? – Erwin Bolwidt Jun 05 '18 at 06:25
  • @ErwinBolwidt I need the text to store it for later purpose. Can you suggest something on getting the data as text that can be easily displayed across devices? – Jashan Singh Jun 05 '18 at 06:34
  • I think I just did in my comment above. – Erwin Bolwidt Jun 05 '18 at 06:39

1 Answers1

1

If you need the binary output from the encryption method as a string, you can use java.util.Base64 to encode it as such.

In practice, it would look something like:

import java.util.Base64;

...

KeysetHandle keysetHandle = KeysetHandle.generateNew(AeadKeyTemplates.AES256_GCM);
Aead aead = AeadFactory.getPrimitive(keysetHandle);
byte [] str1 = str.getBytes("UTF-8");

...

byte [] output = aead.encrypt(str1, str2);
String outputStr = Base64.getEncoder().encodeToString(output);

...
chuckx
  • 6,484
  • 1
  • 22
  • 23