본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

How to: 암호화 API 사용하기

원문 보기 위키 갱신

파일을 암호화하고 복호화하는 방법 알아보기 이제 Dapr 빌딩 블록으로서의 암호화에 대해 읽었으니, SDK를 사용해 암호화 API를 어떻게 쓰는지 함께 살펴볼게요.

Note

Dapr 암호화는 현재 alpha 단계예요.

출처: Dapr 문서

본문

암호화

  • Python
  • JavaScript
  • .NET
  • Go

프로젝트에서 Dapr SDK를 gRPC API와 함께 사용하면 파일이나 문자열 같은 데이터 스트림을 암호화할 수 있어요:


def encrypt_decrypt_string(dapr: DaprClient):
    message = 'The secret is "passw0rd"'


    resp = dapr.encrypt(
        data=message.encode(),
        options=EncryptOptions(

            component_name=CRYPTO_COMPONENT_NAME,

            key_name=RSA_KEY_NAME,


            key_wrap_algorithm='RSA',
        ),
    )


    encrypt_bytes = resp.read()
    print(f'Encrypted the message, got {len(encrypt_bytes)} bytes')

프로젝트에서 Dapr SDK를 gRPC API와 함께 사용하면 버퍼나 문자열에 있는 데이터를 암호화할 수 있어요:

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

이 API들은 스트림과 함께 사용해, 스트림에서 데이터가 올 때 더 효율적으로 암호화할 수도 있어요. 아래 예시는 스트림을 사용해 파일을 암호화하고 다른 파일에 쓰는 방법을 보여줘요:

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

프로젝트에서 Dapr SDK를 gRPC API와 함께 사용하면 문자열이나 바이트 배열의 데이터를 암호화할 수 있어요:

using var client = new DaprClientBuilder().Build();

const string componentName = "azurekeyvault"; //Change this to match your cryptography component
const string keyName = "myKey"; //Change this to match the name of the key in your cryptographic store

const string plainText = "This is the value we're going to encrypt today";

//Encode the string to a UTF-8 byte array and encrypt it
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
var encryptedBytesResult = await client.EncryptAsync(componentName, plaintextBytes, keyName, new EncryptionOptions(KeyWrapAlgorithm.Rsa));

프로젝트에서 Dapr SDK를 사용하면 파일 같은 데이터 스트림을 암호화할 수 있어요.

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

다음 예시는 Encrypt API를 실제 상황에 놓고, 파일을 읽고 암호화한 다음 그 결과를 다른 파일에 저장하는 코드를 보여줘요.

// Input file, clear-text
rf, err := os.Open("input")
if err != nil {
    panic(err)
}
defer rf.Close()

// Output file, encrypted
wf, err := os.Create("output.enc")
if err != nil {
    panic(err)
}
defer wf.Close()

// Encrypt the data using Dapr
out, err := sdkClient.Encrypt(context.Background(), rf, dapr.EncryptOptions{
    // These are the 3 required parameters
    ComponentName: "mycryptocomponent",
    KeyName: "mykey",
    Algorithm: "RSA",
})
if err != nil {
    panic(err)
}

// Read the stream and copy it to the out file
n, err := io.Copy(wf, out)
if err != nil {
    panic(err)
}
fmt.Println("Written", n, "bytes")

다음 예시는 Encrypt API를 사용해 문자열을 암호화해요.

// Input string
rf := strings.NewReader("Amor, ch’a nullo amato amar perdona, mi prese del costui piacer sì forte, che, come vedi, ancor non m’abbandona")

// Encrypt the data using Dapr
enc, err := sdkClient.Encrypt(context.Background(), rf, dapr.EncryptOptions{
    ComponentName: "mycryptocomponent",
    KeyName: "mykey",
    Algorithm: "RSA",
})
if err != nil {
    panic(err)
}

// Read the encrypted data into a byte slice
enc, err := io.ReadAll(enc)
if err != nil {
    panic(err)
}

복호화

  • Python
  • JavaScript
  • .NET
  • Go

데이터 스트림을 복호화하려면 decrypt를 사용해요.

def encrypt_decrypt_string(dapr: DaprClient):
    message = 'The secret is "passw0rd"'




    resp = dapr.decrypt(
        data=encrypt_bytes,
        options=DecryptOptions(

            component_name=CRYPTO_COMPONENT_NAME,

            key_name=RSA_KEY_NAME,
        ),
    )


    decrypt_bytes = resp.read()
    print(f'Decrypted the message, got {len(decrypt_bytes)} bytes')

    print(decrypt_bytes.decode())
    assert message == decrypt_bytes.decode()

Dapr SDK를 사용하면 버퍼나 스트림의 데이터를 복호화할 수 있어요.

// When passing data as a buffer, `decrypt` returns a Buffer with the decrypted message
const plaintext = await client.crypto.decrypt(ciphertext, {
    // Only required option is the component name
    componentName: "mycryptocomponent",
});

// `decrypt` can also be used as a Duplex stream
await pipeline(
    fs.createReadStream("ciphertext.out"),
    await client.crypto.decrypt({
        // Only required option is the component name
        componentName: "mycryptocomponent",
    }),
    fs.createWriteStream("plaintext.out"),
);

문자열을 복호화하려면 프로젝트에서 DecryptAsync gRPC API를 사용해요. 다음 예시에서는 (위 예시에서 얻은) 바이트 배열을 가져와 UTF-8로 인코딩된 문자열로 복호화할게요.

public async Task<string> DecryptBytesAsync(byte[] encryptedBytes)
{
    using var client = new DaprClientBuilder().Build();

    const string componentName = "azurekeyvault"; //Change this to match your cryptography component
    const string keyName = "myKey"; //Change this to match the name of the key in your cryptographic store

    var decryptedBytes = await client.DecryptAsync(componentName, encryptedBytes, keyName);
    var decryptedString = Encoding.UTF8.GetString(decryptedBytes.ToArray());
    return decryptedString;
}

파일을 복호화하려면 프로젝트에서 Decrypt gRPC API를 사용해요. 다음 예시에서 out은 위 예시들처럼 파일에 쓰거나 메모리에서 읽을 수 있는 스트림이에요.

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

다음 단계

암호화 컴포넌트 스펙

더 알아보기 (Learn more)