Google Tink多语言跨平台加密演示

Tikn是什么

由Google的密码学家和安全工程师联合编写的加密库。源于与Google产品团队合作的丰富经验,提供了即便没有加密经验也可以安全使用的API。

GitHub源码地址: https://github.com/google/tink

通过官方demo我们可以知道Tink的使用方式。

 maven配置方式导入依赖

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

gradle 配置方式导入依赖

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

 demo演示:

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 目前除了支持 java 外,还支持 Android、C++、Obj-C

发布了87 篇原创文章 · 获赞 205 · 访问量 35万+

猜你喜欢

转载自blog.csdn.net/weixin_43970743/article/details/104299266