Google Tink multi-language cross-platform encryption demo

What is Tikn

By Google's security engineers and cryptographers prepared jointly encryption library. Comes from extensive experience in working with Google product teams, providing experience even without encryption can also be safe to use API.

GitHub Source Address:  https://github.com/google/tink

By official demo we can know Tink's use.

 Import-dependent configuration maven

<dependency>
  <groupId>com.google.crypto.tink</groupId>
  <artifactId>tink</artifactId>
  <version>1.2.0</version>
</dependency>

Import-dependent configuration gradle

dependencies {
    compile("com.google.crypto.tink:tink:1.2.0")
}

 demo Demonstration:

import com.google.crypto.tink.Aead;
import com.google.crypto.tink.KeysetHandle;
import com.google.crypto.tink.aead.AeadFactory;
import com.google.crypto.tink.aead.AeadKeyTemplates;
import com.google.crypto.tink.config.TinkConfig;

import java.io.IOException;
import java.security.GeneralSecurityException;


public class TinkDemo {

    public static void main(String[] args) throws GeneralSecurityException, IOException {
        // 基于默认配置进行注册
        TinkConfig.register();
        // 测试用的明文字符串
        String plaintext = "明文";
        // 生成密钥
        KeysetHandle keysetHandle = KeysetHandle.generateNew(AeadKeyTemplates.AES256_CTR_HMAC_SHA256);
        // 使用密钥材料获取所选的基元的实例
        Aead aead = AeadFactory.getPrimitive(keysetHandle);

        /*
         * 加密
         * 第一个参数是plaintext(明文)
         * 第二个参数是associatedData(相关数据)
         *     可以为null,相当于一个空(零长度)字节数组。
         *     同样,解密时必须提供同样的相关数据。
         */

        // 使用基元实例来完成加密任务
        byte[] ciphertext = aead.encrypt(plaintext.getBytes(),null);
        // 解密
        byte[] decrypted = aead.decrypt(ciphertext, null);

        System.out.println(new String(decrypted));
        System.out.println(ciphertext);
    }
}


Tink exception java support, but also support Android, C ++, Obj-C

Published 87 original articles · won praise 205 · Views 350,000 +

Guess you like

Origin blog.csdn.net/weixin_43970743/article/details/104299266