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

Quickstart: Cryptography

원문 보기 위키 갱신

Dapr Cryptography 빌딩 블록으로 시작해 봐요.

Alpha

cryptography 빌딩 블록은 현재 alpha 단계예요.

Dapr cryptography 빌딩 블록을 살펴볼게요. 이 Quickstart에서는 Dapr 암호화 API를 사용해 데이터를 암호화하고 복호화하는 어플리케이션을 만들 거예요. 다음을 할 거예요.

  • 짧은 문자열을 (RSA 키를 사용해) 암호화한 뒤 복호화하고, 결과를 Go byte slice로 메모리에서 읽어요.
  • 큰 파일을 (AES 키를 사용해) 암호화한 뒤 복호화하고, 스트림을 사용해 암호화/복호화된 데이터를 파일로 저장해요.

참고

이 예제는 gRPC를 활용하는 Dapr SDK를 사용해요. 암호화 API로 메시지를 암호화/복호화할 때는 SDK를 강력히 권장해요.

현재 cryptography API는 Go SDK로 체험할 수 있어요.

  • JavaScript
  • Go

이 quickstart에는 crypto-quickstart라는 JavaScript 어플리케이션이 포함돼요.

출처: Dapr 문서

본문

사전 조건 (Pre-requisites)

이 예제에 필요한 것들:

  • Dapr CLI와 초기화된 환경.

  • 최신 Node.js 설치.

  • Docker Desktop.

  • 시스템에 OpenSSL 사용 가능.

1단계: 환경 설정하기

Quickstarts 저장소에 제공된 샘플을 클론해요.

git clone https://github.com/dapr/quickstarts.git

터미널에서 루트 디렉터리부터 cryptography 샘플로 이동해요.

cd cryptography/javascript/sdk

소스 코드가 있는 폴더로 들어가요.

cd ./crypto-quickstart

의존성을 설치해요.

npm install

2단계: Dapr로 어플리케이션 실행하기

어플리케이션 코드에는 두 개의 필수 키가 정의돼 있어요.

  • 개인 RSA 키
  • 256비트 대칭(AES) 키

OpenSSL로 RSA 키와 AES 키 두 개를 생성하고 두 파일에 작성해요.

mkdir -p keys
# Generate a private RSA key, 4096-bit keys
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:4096 -out keys/rsa-private-key.pem
# Generate a 256-bit key for AES
openssl rand -out keys/symmetric-key-256 32

Go 서비스 앱을 Dapr로 실행해요.

dapr run --app-id crypto-quickstart --resources-path ../../../components/ -- npm start

예상 출력

== APP == 2023-10-25T14:30:50.435Z INFO [GRPCClient, GRPCClient] Opening connection to 127.0.0.1:58173
== APP == == Encrypting message using buffers
== APP == Encrypted the message, got 856 bytes
== APP == == Decrypting message using buffers
== APP == Decrypted the message, got 24 bytes
== APP == The secret is "passw0rd"
== APP == == Encrypting message using streams
== APP == Encrypting federico-di-dio-photography-Q4g0Q-eVVEg-unsplash.jpg to encrypted.out
== APP == Encrypted the message to encrypted.out
== APP == == Decrypting message using streams
== APP == Decrypting encrypted.out to decrypted.out.jpg
== APP == Decrypted the message to decrypted.out.jpg

무슨 일이 일어났나요?

local-storage.yaml

앞서 crypto-quickstarts 안에 keys라는 디렉터리를 만들었어요. local-storage 컴포넌트 YAML에서 path metadata는 새로 만든 keys 디렉터리를 가리켜요.

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: localstorage
spec:
type: crypto.dapr.localstorage
version: v1
metadata:
- name: path
# Path is relative to the folder where the example is located
value: ./keys

index.mjs

어플리케이션 파일은 생성한 RSA 및 AES 키를 사용해 메시지와 파일을 암호화/복호화해요. 어플리케이션은 새 Dapr SDK 클라이언트를 만들어요.

async function start() {
const client = new DaprClient({
daprHost,
daprPort,
communicationProtocol: CommunicationProtocolEnum.GRPC,
});

// Encrypt and decrypt a message from a buffer
await encryptDecryptBuffer(client);

// Encrypt and decrypt a message using streams
await encryptDecryptStream(client);
}

RSA 키를 사용해 문자열 암호화 및 복호화 클라이언트가 생성되면 어플리케이션이 메시지를 암호화해요.

async function encryptDecryptBuffer(client) {
// Message to encrypt
const plaintext = `The secret is "passw0rd"`

// First, encrypt the message
console.log("== Encrypting message using buffers");

const encrypted = await client.crypto.encrypt(plaintext, {
componentName: "localstorage",
keyName: "rsa-private-key.pem",
keyWrapAlgorithm: "RSA",
});

console.log("Encrypted the message, got", encrypted.length, "bytes");

그런 다음 어플리케이션이 메시지를 복호화해요.

// Decrypt the message
console.log("== Decrypting message using buffers");
const decrypted = await client.crypto.decrypt(encrypted, {
componentName: "localstorage",
});

console.log("Decrypted the message, got", decrypted.length, "bytes");
console.log(decrypted.toString("utf8"));

// ...
}

AES 키를 사용해 큰 파일 암호화 및 복호화 다음으로 어플리케이션이 큰 이미지 파일을 암호화해요.

async function encryptDecryptStream(client) {
// First, encrypt the message
console.log("== Encrypting message using streams");
console.log("Encrypting", testFileName, "to encrypted.out");

await pipeline(
createReadStream(testFileName),
await client.crypto.encrypt({
componentName: "localstorage",
keyName: "symmetric-key-256",
keyWrapAlgorithm: "A256KW",
}),
createWriteStream("encrypted.out"),
);

console.log("Encrypted the message to encrypted.out");

그런 다음 어플리케이션이 큰 이미지 파일을 복호화해요.

// Decrypt the message
console.log("== Decrypting message using streams");
console.log("Decrypting encrypted.out to decrypted.out.jpg");
await pipeline(
createReadStream("encrypted.out"),
await client.crypto.decrypt({
componentName: "localstorage",
}),
createWriteStream("decrypted.out.jpg"),
);

console.log("Decrypted the message to decrypted.out.jpg");
}

이 quickstart에는 crypto-quickstart라는 Go 어플리케이션도 포함돼요.

사전 조건 (Pre-requisites)

이 예제에 필요한 것들:

  • Dapr CLI와 초기화된 환경.

  • 최신 버전의 Go.

  • Docker Desktop.

  • 시스템에 OpenSSL 사용 가능.

1단계: 환경 설정하기

Quickstarts 저장소에 제공된 샘플을 클론해요.

git clone https://github.com/dapr/quickstarts.git

터미널에서 루트 디렉터리부터 cryptography 샘플로 이동해요.

cd cryptography/go/sdk

2단계: Dapr로 어플리케이션 실행하기

소스 코드가 있는 폴더로 들어가요.

cd ./crypto-quickstart

어플리케이션 코드에는 두 개의 필수 키가 정의돼 있어요.

  • 개인 RSA 키
  • 256비트 대칭(AES) 키

OpenSSL로 RSA 키와 AES 키 두 개를 생성하고 두 파일에 작성해요.

mkdir -p keys
# Generate a private RSA key, 4096-bit keys
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:4096 -out keys/rsa-private-key.pem
# Generate a 256-bit key for AES
openssl rand -out keys/symmetric-key-256 32

Go 서비스 앱을 Dapr로 실행해요.

dapr run --app-id crypto-quickstart --resources-path ../../../components/ -- go run .

예상 출력

== APP == dapr client initializing for: 127.0.0.1:52407
== APP == Encrypted the message, got 856 bytes
== APP == Decrypted the message, got 24 bytes
== APP == The secret is "passw0rd"
== APP == Wrote decrypted data to encrypted.out
== APP == Wrote decrypted data to decrypted.out.jpg

무슨 일이 일어났나요?

local-storage.yaml

앞서 crypto-quickstarts 안에 keys라는 디렉터리를 만들었어요. local-storage 컴포넌트 YAML에서 path metadata는 새로 만든 keys 디렉터리를 가리켜요.

apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: localstorage
spec:
type: crypto.dapr.localstorage
version: v1
metadata:
- name: path
# Path is relative to the folder where the example is located
value: ./keys

app.go

어플리케이션 파일은 생성한 RSA 및 AES 키를 사용해 메시지와 파일을 암호화/복호화해요. 어플리케이션은 새 Dapr SDK 클라이언트를 만들어요.

func main() {
// Create a new Dapr SDK client
client, err := dapr.NewClient()

//...

// Step 1: encrypt a string using the RSA key, then decrypt it and show the output in the terminal
encryptDecryptString(client)

// Step 2: encrypt a large file and then decrypt it, using the AES key
encryptDecryptFile(client)
}

RSA 키를 사용해 문자열 암호화 및 복호화 클라이언트가 생성되면 어플리케이션이 메시지를 암호화해요.

func encryptDecryptString(client dapr.Client) {
// ...

// Encrypt the message
encStream, err := client.Encrypt(context.Background(),
strings.NewReader(message),
dapr.EncryptOptions{
ComponentName: CryptoComponentName,
// Name of the key to use
// Since this is a RSA key, we specify that as key wrapping algorithm
KeyName: RSAKeyName,
KeyWrapAlgorithm: "RSA",
},
)

// ...

// The method returns a readable stream, which we read in full in memory
encBytes, err := io.ReadAll(encStream)
// ...

fmt.Printf("Encrypted the message, got %d bytes\n", len(encBytes))

그런 다음 어플리케이션이 메시지를 복호화해요.

// Now, decrypt the encrypted data
decStream, err := client.Decrypt(context.Background(),
bytes.NewReader(encBytes),
dapr.DecryptOptions{
// We just need to pass the name of the component
ComponentName: CryptoComponentName,
// Passing the name of the key is optional
KeyName: RSAKeyName,
},
)

// ...

// The method returns a readable stream, which we read in full in memory
decBytes, err := io.ReadAll(decStream)

// ...

// Print the message on the console
fmt.Printf("Decrypted the message, got %d bytes\n", len(decBytes))
fmt.Println(string(decBytes))
}

AES 키를 사용해 큰 파일 암호화 및 복호화 다음으로 어플리케이션이 큰 이미지 파일을 암호화해요.

func encryptDecryptFile(client dapr.Client) {
const fileName = "liuguangxi-66ouBTTs_x0-unsplash.jpg"

// Get a readable stream to the input file
plaintextF, err := os.Open(fileName)

// ...

defer plaintextF.Close()

// Encrypt the file
encStream, err := client.Encrypt(context.Background(),
plaintextF,
dapr.EncryptOptions{
ComponentName: CryptoComponentName,
// Name of the key to use
// Since this is a symmetric key, we specify AES as key wrapping algorithm
KeyName: SymmetricKeyName,
KeyWrapAlgorithm: "AES",
},
)

// ...

// Write the encrypted data to a file "encrypted.out"
encryptedF, err := os.Create("encrypted.out")

// ...

encryptedF.Close()

fmt.Println("Wrote decrypted data to encrypted.out")

그런 다음 어플리케이션이 큰 이미지 파일을 복호화해요.

// Now, decrypt the encrypted data
// First, open the file "encrypted.out" again, this time for reading
encryptedF, err = os.Open("encrypted.out")

// ...

defer encryptedF.Close()

// Now, decrypt the encrypted data
decStream, err := client.Decrypt(context.Background(),
encryptedF,
dapr.DecryptOptions{
// We just need to pass the name of the component
ComponentName: CryptoComponentName,
// Passing the name of the key is optional
KeyName: SymmetricKeyName,
},
)

// ...

// Write the decrypted data to a file "decrypted.out.jpg"
decryptedF, err := os.Create("decrypted.out.jpg")

// ...

decryptedF.Close()

fmt.Println("Wrote decrypted data to decrypted.out.jpg")
}

데모 보기

Dapr Community Call #83의 cryptography API 데모 영상을 시청해 봐요.

의견을 들려주세요!

우린 Quickstart 예제를 계속 개선하고 있고 여러분의 피드백을 소중히 여겨요. 이 Quickstart가 도움이 됐나요? 개선할 제안이 있나요? Discord Server에 참여해서 의견을 공유해 주세요.

다음 단계

  • cryptography API로 암호화/복호화하는 더 많은 예제를 살펴봐요
  • Dapr 빌딩 블록으로서의 cryptography에 대해 더 알아봐요

Dapr tutorials 탐색하기 >>

더 알아보기 (Learn more)