如何使用加密API

学习如何加密和解密文件

现在您已经阅读了 Dapr密码学构建块,让我们通过使用SDK与密码学API一起进行演示。

注意

Dapr密码学目前处于alpha阶段。

加密

使用 Dapr SDK 在您的项目中,通过 gRPC API,您可以在缓冲区或字符串中加密数据:

  1. // When passing data (a buffer or string), `encrypt` returns a Buffer with the encrypted message
  2. const ciphertext = await client.crypto.encrypt(plaintext, {
  3. // Name of the Dapr component (required)
  4. componentName: "mycryptocomponent",
  5. // Name of the key stored in the component (required)
  6. keyName: "mykey",
  7. // Algorithm used for wrapping the key, which must be supported by the key named above.
  8. // Options include: "RSA", "AES"
  9. keyWrapAlgorithm: "RSA",
  10. });

当数据来自流时,API也可以与流一起使用,以更高效地对数据进行加密。 以下示例使用流将文件加密,并将结果写入另一个文件:

  1. // `encrypt` can be used as a Duplex stream
  2. await pipeline(
  3. fs.createReadStream("plaintext.txt"),
  4. await client.crypto.encrypt({
  5. // Name of the Dapr component (required)
  6. componentName: "mycryptocomponent",
  7. // Name of the key stored in the component (required)
  8. keyName: "mykey",
  9. // Algorithm used for wrapping the key, which must be supported by the key named above.
  10. // Options include: "RSA", "AES"
  11. keyWrapAlgorithm: "RSA",
  12. }),
  13. fs.createWriteStream("ciphertext.out"),
  14. );

在您的项目中使用 Dapr SDK,您可以对数据流进行加密,例如文件。

  1. out, err := sdkClient.Encrypt(context.Background(), rf, dapr.EncryptOptions{
  2. // Name of the Dapr component (required)
  3. ComponentName: "mycryptocomponent",
  4. // Name of the key stored in the component (required)
  5. KeyName: "mykey",
  6. // Algorithm used for wrapping the key, which must be supported by the key named above.
  7. // Options include: "RSA", "AES"
  8. Algorithm: "RSA",
  9. })

以下示例将 Encrypt API 放入上下文中,使用代码读取文件,对其进行加密,然后将结果存储在另一个文件中。

  1. // Input file, clear-text
  2. rf, err := os.Open("input")
  3. if err != nil {
  4. panic(err)
  5. }
  6. defer rf.Close()
  7. // Output file, encrypted
  8. wf, err := os.Create("output.enc")
  9. if err != nil {
  10. panic(err)
  11. }
  12. defer wf.Close()
  13. // Encrypt the data using Dapr
  14. out, err := sdkClient.Encrypt(context.Background(), rf, dapr.EncryptOptions{
  15. // These are the 3 required parameters
  16. ComponentName: "mycryptocomponent",
  17. KeyName: "mykey",
  18. Algorithm: "RSA",
  19. })
  20. if err != nil {
  21. panic(err)
  22. }
  23. // Read the stream and copy it to the out file
  24. n, err := io.Copy(wf, out)
  25. if err != nil {
  26. panic(err)
  27. }
  28. fmt.Println("Written", n, "bytes")

以下示例使用 Encrypt API 对字符串进行加密。

  1. // Input string
  2. rf := strings.NewReader("Amor, ch’a nullo amato amar perdona, mi prese del costui piacer sì forte, che, come vedi, ancor non m’abbandona")
  3. // Encrypt the data using Dapr
  4. enc, err := sdkClient.Encrypt(context.Background(), rf, dapr.EncryptOptions{
  5. ComponentName: "mycryptocomponent",
  6. KeyName: "mykey",
  7. Algorithm: "RSA",
  8. })
  9. if err != nil {
  10. panic(err)
  11. }
  12. // Read the encrypted data into a byte slice
  13. enc, err := io.ReadAll(enc)
  14. if err != nil {
  15. panic(err)
  16. }

使用 Dapr SDK 在您的项目中,通过 gRPC API,您可以在字符串或字节数组中加密数据:

  1. using var client = new DaprClientBuilder().Build();
  2. const string componentName = "azurekeyvault"; //Change this to match your cryptography component
  3. const string keyName = "myKey"; //Change this to match the name of the key in your cryptographic store
  4. const string plainText = "This is the value we're going to encrypt today";
  5. //Encode the string to a UTF-8 byte array and encrypt it
  6. var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
  7. var encryptedBytesResult = await client.EncryptAsync(componentName, plaintextBytes, keyName, new EncryptionOptions(KeyWrapAlgorithm.Rsa));

解密

使用 Dapr SDK,您可以使用缓冲区或流解密数据。

  1. // When passing data as a buffer, `decrypt` returns a Buffer with the decrypted message
  2. const plaintext = await client.crypto.decrypt(ciphertext, {
  3. // Only required option is the component name
  4. componentName: "mycryptocomponent",
  5. });
  6. // `decrypt` can also be used as a Duplex stream
  7. await pipeline(
  8. fs.createReadStream("ciphertext.out"),
  9. await client.crypto.decrypt({
  10. // Only required option is the component name
  11. componentName: "mycryptocomponent",
  12. }),
  13. fs.createWriteStream("plaintext.out"),
  14. );

要解密文件,请使用 Decrypt gRPC API 到您的项目。

在下面的示例中,out 是一个可以写入文件或在内存中读取的流,就像上面的示例一样。

  1. out, err := sdkClient.Decrypt(context.Background(), rf, dapr.EncryptOptions{
  2. // Only required option is the component name
  3. ComponentName: "mycryptocomponent",
  4. })

要解密字符串,请在您的项目中使用 ‘DecryptAsync’ gRPC API。

在下面的示例中,我们将使用一个字节数组(例如上面的示例)对其进行解密,得到一个UTF-8编码的字符串。

  1. public async Task<string> DecryptBytesAsync(byte[] encryptedBytes)
  2. {
  3. using var client = new DaprClientBuilder().Build();
  4. const string componentName = "azurekeyvault"; //Change this to match your cryptography component
  5. const string keyName = "myKey"; //Change this to match the name of the key in your cryptographic store
  6. var decryptedBytes = await client.DecryptAsync(componentName, encryptedBytes, keyName);
  7. var decryptedString = Encoding.UTF8.GetString(decryptedBytes.ToArray());
  8. return decryptedString;
  9. }

下一步

支持的加密组件列表