当前位置:网站首页>Tutorial: encryption keys in cloud (using golang and CLI)
Tutorial: encryption keys in cloud (using golang and CLI)
2022-07-25 05:57:00 【chinadefi】
course :Cloud Encryption key in ( Use Golang and CLI)


As we increasingly turn to the public cloud , The use of encryption keys is also becoming more and more important . This includes encrypting data and digital signatures . Its advantages include :
- Encryption in the cloud . This allows us to encrypt data in the cloud , Instead of processing data on the client machine .
- Access strategy . Use cloud based systems , You can define strict access policies for the use of encryption keys .
- Audit . adopt AWS CloudTrail, Access to encryption keys can be recorded , This can support regulation and the need for compliance .
- BYOK. This allows users to create their own keys , Then upload them to the cloud .
stay AWS in , We have KMS( Key management service ), It generates and stores encryption keys . These keys will never leave Amazon Of HSM( Hardware security module ), And according to FIPS 140–2 It was verified . Export time , They are only provided in encrypted form . in general , The cost of storing a key is per month 1 dollar ( But for AWS The key generated by the service is stored for free ). The use of the key is not limited by the access threshold . Besides , Keys can only be used in the geographical area where they are set .

Symmetric or asymmetric key
The encryption key is kept in AWS In a trusted hardware environment , Locked to a specific area , And it is applied to AWS IAM( Identity and access management ) Strict access policies related to identifiers . These are related to the minimum privilege —— Unless permissions are defined in the access policy , Otherwise, permission will not be granted .
first , We can create symmetric keys ( Is used to encrypt / Decrypt or generate HMAC) Or asymmetric key ( Used for encryption or digital signature ). Use HMAC, We create a symmetric key , This key can be used to sign messages , Then verify the signature with the same key . Digital signature , We use a private ( Secret ) The key signs the message , Then it is verified by a public key .
stay AWS Control , We can use the following command to create a symmetric key :

The generated key has a key ID, We defined its purpose ( Such as encryption and decryption ):

then , User defined key aliases and ARN (Amazon Resource Names). Next , We can define a policy for the use of keys :
{
"Id": "key-consolepolicy-3",
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Enable IAM User Permissions",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::960039751898:root"
},
"Action": "kms:*",
"Resource": "*"
},
{
"Sid": "Allow access for Key Administrators",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::960039751898:user/bill"
},
"Action": [
"kms:Create*",
"kms:Describe*",
"kms:Enable*",
"kms:List*",
"kms:Put*",
"kms:Update*",
"kms:Revoke*",
"kms:Disable*",
"kms:Get*",
"kms:Delete*",
"kms:TagResource",
"kms:UntagResource",
"kms:ScheduleKeyDeletion",
"kms:CancelKeyDeletion"
],
"Resource": "*"
},
{
"Sid": "Allow use of the key",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::960039751898:user/bill"
},
"Action": [
"kms:Encrypt",
"kms:Decrypt",
"kms:ReEncrypt*",
"kms:GenerateDataKey*",
"kms:DescribeKey"
],
"Resource": "*"
},
{
"Sid": "Allow attachment of persistent resources",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::960039751898:user/bill"
},
"Action": [
"kms:CreateGrant",
"kms:ListGrants",
"kms:RevokeGrant"
],
"Resource": "*",
"Condition": {
"Bool": {
"kms:GrantIsForAWSResource": "true"
}
}
}
]
}
In this case , We will see that only users are allowed to encrypt and decrypt , However, other users are not allowed to perform these operations . Then from Key ID and ARN Describe the key created :

Now we can write a Golang Program , Use this key to encrypt plaintext , And then decrypt it . We first need to define AWS Areas and ARN. meanwhile , We also AWS_Access_Key_ID and AWS_Secret_Access_Key Defined AWS voucher . They can be defined in the program , It can also be in ~/.aws/credentials Folder In the definition of :
package mainimport (
"fmt""os""github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kms"
"github.com/aws/aws-sdk-go/aws/credentials"
)func main() {message := "This is a secret"
const keyID = "arn:aws:kms:us-east-1:904269751807:key/9954354-f122-45f9-b6c6-29e571562a22"argCount := len(os.Args[1:])if argCount > 0 {
message = os.Args[1]
}creds := credentials.NewStaticCredentials("AWS_Access_Key_ID", "AWS_Secret_Access_Key", "")sess, _ := session.NewSession(&aws.Config{Region: aws.String("us-east-1"), Credentials: creds})svc := kms.New(sess)encMethod := &kms.EncryptInput{KeyId: aws.String(keyID), Plaintext: []byte(message)}cipherText, _:= svc.Encrypt(encMethod)fmt.Printf("Input: %s\n", message)
fmt.Printf("Encrypted: %x\n", cipherText.CiphertextBlob)
inputDecrypt := &kms.DecryptInput{CiphertextBlob: cipherText.CiphertextBlob}
respDecrypt, _ := svc.Decrypt(inputDecrypt)fmt.Printf("Decrypted: %s\n", string(respDecrypt.Plaintext))
}
A running example :
Input: Testing 12345
Encrypted: 0102020078eba286059ff61e64dc8414c5fc8ff716dda2c8c47903983373a262fcc3a1503a01bfe78037a671257e78e683cd5483b3f00000006b306906092a864886f70d010706a05c305a020100305506092a864886f70d010701301e060960864801650304012e3011040c0516bdc01f1edea632e7fd6102011080282531e65f367891af4ac6c418bf804bbe0bed2e008e30cb93670089c83dc44e7e94950770b8a70488
Decrypted: Testing 12345
AWS CLI Encryption and decryption
In addition to using programming languages , We can also use CLI Perform the operation . Create key :
aws kms create-key --tags TagKey=Purpose, TagValue=MyKey --description "For testing
We can list our keys from the alias :
\> **aws kms list-aliases**
{
"Aliases": [
{
"AliasName": "alias/Test01",
"AliasArn": "arn:aws:kms:us-east-1:**904269751807**:alias/Test01",
"TargetKeyId": "9954354-f122-45f9-b6c6-29e571562a22",
"CreationDate": 1657877917.647,
"LastUpdatedDate": 1657877917.647
},
then , We can encrypt plaintext messages in the following ways “Hello 123”:
aws kms encrypt --plaintext hello.txt --key-id="9954354-f122-45f9-b1c3-29e571562a22" --encryption-context purpose=test
{
"CiphertextBlob": "AQICAHjrooYFn/YeZNyEFMX8j/cW3aLIxHkDmDNzomL8w6FQOgE+rt03vmCwrYR5fP153zPjAAAAZzBlBgkqhkiG9w0BBwagWDBWAgEAMFEGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMNvsXMqFmyq7j5tMeAgEQgCSrzEA0EJEgrstoNvnbVfH/EaptXzqeOwADaRLMvhDo7F9G6nM=",
"KeyId": "arn:aws:kms:us-east-1:904269751807:key/9954354-f122-45f9-b6c6-29e571562a22",
"EncryptionAlgorithm": "SYMMETRIC_DEFAULT"
}
Now we can see that we have “AQICAH…m4sE=” The ciphertext of . Next , Can be decrypted :
aws kms decrypt --ciphertext-blob "AQICAHjrooYFn/YeZNyEFMX8j/cW3aLIxHkDmDNzomL8w6FQOgEnx2HXcpIIObK9qjHFGit3AAAAZzBlBgkqhkiG9w0BBwagWDBWAgEAMFEGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQM/qzr60lyQS5A5yZ8AgEQgCQueKSLpCjdQiYHKWPX3NUT87cOvcmrT/RDYlBcDge7Ymzm4sE=" --key-id "9954354-d28-45f9-b1c3-29e571562a22"
Asymmetric keys and HMAC
Use asymmetric key , We can choose RSA 2K、3K or 4K:

For digital signatures , We can add P256、P521、sepc256k1 Elliptic curve method :

Conclusion
One of the most costly events in network security is the destruction of trust infrastructure . therefore , Key management and control are very important , Storing them in the cloud brings many benefits . meanwhile , We have seen too many data leaks , The use of encryption can reduce the scope of data leakage to almost zero —— But we must make sure that our keys are kept securely , At least in a secret way .
These keys are our most important secrets , So don't be locked in a cloud provider , And there are still people entering our AWS Environment and discover the risk of our key .
I created a demo here :
https://asecuritysite.com/golang/go_aws
Source:https://medium.com/asecuritysite-when-bob-met-alice/encryption-keys-in-the-cloud-366f091fe90e
About
ChinaDeFi - ChinaDeFi.com It's a research driven DeFi Innovation organizations , We are also a blockchain development team . From all over the world every day 500 Close to a good source of information 900 In the content , Looking for deeper thinking 、 Sort out more systematic content , Provide decision-making assistant materials to the Chinese market at the fastest speed .
Layer 2 friends sharing same hobby - Welcome to Layer 2 Interested blockchain technology enthusiasts 、 Study and analyze people and Gavin( WeChat : chinadefi) contact , Discuss together Layer 2 Landing opportunities . Please pay attention to our official account of WeChat “ Decentralized financial community ”.

边栏推荐
猜你喜欢

Amazoncaptcha bypasses Amazon IP verification code with 95% success rate

(Niuke multi school I in 2022) i-chiitoitsu (expected DP)
![Atof(), atoi(), atol() functions [detailed]](/img/5a/a421eab897061c61467c272f122202.jpg)
Atof(), atoi(), atol() functions [detailed]

HTB-Optimum
![[ultra detailed diagram] FPN + mask RCNN](/img/ef/ddd62fe7e54074c134aa5ee4cc5840.png)
[ultra detailed diagram] FPN + mask RCNN

The selection reference of Junzheng T41, T40 and T31 versions are all here

Linear algebra (3)

50 places are limited to open | with the news of oceanbase's annual press conference coming!

Microservice gateway component

Brief introduction of acoustic filter Market
随机推荐
HTB-Optimum
Leetcode 202. 快乐数(一点都不快乐)
ROI pooling and ROI align
Analyzing the principle of DNS resolution in kubernetes cluster
Leetcode 0122. the best time to buy and sell stocks II
Vim配置Golang开发环境
sqlilabs less-28~less-8a
传输线理论之相速、相位等的概念
[daily practice] day (14)
Siggraph 2022 -- rendering iridescent rock dove neck feathers
Programming hodgepodge (I)
暑期总结2
PostgreSQL learning 04 PG_ hint_ Plan installation and use, SQL optimization knowledge
Differences and application directions of GPS, base station and IP positioning
Leetcode 237. delete nodes in the linked list
Sword finger offer 54. the k-th node of the binary search tree
R language uses LM function to build multiple linear regression model and write regression equation according to model coefficient
动态规划学习笔记
Dynamic planning learning notes
R language ggpubr package ggarrange function combines multiple images and annotates_ Figure add annotation, annotation, annotation information for the combined image, and use the right parameter to ad