Skip to main content

加密 REST API 的机密

多个 REST API 终结点可让你在 上创建机密。 要使用这些终结点,必须使用 libsodium 加密机密值。 有关详细信息,请参阅 libsodium 文档

要加密机密,需要 Base64 编码的公钥。 你可以从 REST API 获取公钥。 要确定用于获取公钥的终结点,请查看用于创建机密的终结点中的 encrypted_value 参数的文档。

如果使用的是 Node.js,你可以使用 libsodium-wrappers 库加密机密。 有关详细信息,请参阅 libsodium-wrappers

在以下示例中,将 YOUR_SECRET 替换为要加密的纯文本值。 将 YOUR_BASE64_KEY 替换为 Base64 编码的公钥。 用于创建机密的终结点的文档将告诉你可以使用哪个终结点来获取公钥。 ORIGINAL 不是占位符;它是 libsodium-wrappers 库的参数。

JavaScript
const sodium = require('libsodium-wrappers')

const secret = 'YOUR_SECRET'
const key = 'YOUR_BASE64_KEY'

//Check if libsodium is ready and then proceed.
sodium.ready.then(() => {
  // Convert the secret and key to a Uint8Array.
  let binkey = sodium.from_base64(key, sodium.base64_variants.ORIGINAL)
  let binsec = sodium.from_string(secret)

  // Encrypt the secret using libsodium
  let encBytes = sodium.crypto_box_seal(binsec, binkey)

  // Convert the encrypted Uint8Array to Base64
  let output = sodium.to_base64(encBytes, sodium.base64_variants.ORIGINAL)

  // Print the output
  console.log(output)
});

如果使用的是 Python 3,你可以使用 PyNaCl 库加密机密。 有关详细信息,请参阅 PyNaCl

在以下示例中,将 YOUR_SECRET 替换为要加密的纯文本值。 将 YOUR_BASE64_KEY 替换为 Base64 编码的公钥。 用于创建机密的终结点的文档将告诉你可以使用哪个终结点来获取公钥。

Python
from base64 import b64encode
from nacl import encoding, public

def encrypt(public_key: str, secret_value: str) -> str:
  """Encrypt a Unicode string using the public key."""
  public_key = public.PublicKey(public_key.encode("utf-8"), encoding.Base64Encoder())
  sealed_box = public.SealedBox(public_key)
  encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
  return b64encode(encrypted).decode("utf-8")

encrypt("YOUR_BASE64_KEY", "YOUR_SECRET")

如果使用的是 C#,你可以使用 Sodium.Core 包加密机密。 有关详细信息,请参阅 Sodium.Core

在以下示例中,将 YOUR_SECRET 替换为要加密的纯文本值。 将 YOUR_BASE64_KEY 替换为 Base64 编码的公钥。 用于创建机密的终结点的文档将告诉你可以使用哪个终结点来获取公钥。

C#
var secretValue = System.Text.Encoding.UTF8.GetBytes("YOUR_SECRET");
var publicKey = Convert.FromBase64String("YOUR_BASE64_KEY");

var sealedPublicKeyBox = Sodium.SealedPublicKeyBox.Create(secretValue, publicKey);

Console.WriteLine(Convert.ToBase64String(sealedPublicKeyBox));

如果使用的是 Ruby,你可以使用 RbNaCl gem 加密机密。 有关详细信息,请参阅 RbNaCl

在以下示例中,将 YOUR_SECRET 替换为要加密的纯文本值。 将 YOUR_BASE64_KEY 替换为 Base64 编码的公钥。 用于创建机密的终结点的文档将告诉你可以使用哪个终结点来获取公钥。

Ruby
require "rbnacl"
require "base64"

key = Base64.decode64("YOUR_BASE64_KEY")
public_key = RbNaCl::PublicKey.new(key)

box = RbNaCl::Boxes::Sealed.from_public_key(public_key)
encrypted_secret = box.encrypt("YOUR_SECRET")

# Print the base64 encoded secret
puts Base64.strict_encode64(encrypted_secret)