现实世界的加密魔法:让 Go 的加密包发挥作用,Go Crypto 13
来源:dev.to
时间:2025-01-08 15:51:35 417浏览 收藏
今天golang学习网给大家带来了《现实世界的加密魔法:让 Go 的加密包发挥作用,Go Crypto 13》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~
嘿,加密巫师!准备好用 go 的加密包来看看现实世界的魔法了吗?我们已经学习了所有这些很酷的加密咒语,现在让我们将它们用于一些实际的魔法中!我们将创建两个强大的神器:安全文件加密咒语和公钥基础设施 (pki) 召唤仪式。
魔法#1:安全文件加密咒语
让我们创建一个神奇的卷轴,可以使用强大的 aes-gcm(伽罗瓦/计数器模式)魔法安全地加密和解密文件。此咒语提供保密性和完整性保护!
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"fmt"
"io"
"os"
)
// our encryption spell
func encrypt(plaintext []byte, key []byte) ([]byte, error) {
block, err := aes.newcipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.newgcm(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.noncesize())
if _, err := io.readfull(rand.reader, nonce); err != nil {
return nil, err
}
return gcm.seal(nonce, nonce, plaintext, nil), nil
}
// our decryption counter-spell
func decrypt(ciphertext []byte, key []byte) ([]byte, error) {
block, err := aes.newcipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.newgcm(block)
if err != nil {
return nil, err
}
if len(ciphertext) < gcm.noncesize() {
return nil, errors.new("ciphertext too short")
}
nonce, ciphertext := ciphertext[:gcm.noncesize()], ciphertext[gcm.noncesize():]
return gcm.open(nil, nonce, ciphertext, nil)
}
// enchant a file with our encryption spell
func encryptfile(inputfile, outputfile string, key []byte) error {
plaintext, err := os.readfile(inputfile)
if err != nil {
return err
}
ciphertext, err := encrypt(plaintext, key)
if err != nil {
return err
}
return os.writefile(outputfile, ciphertext, 0644)
}
// remove the encryption enchantment from a file
func decryptfile(inputfile, outputfile string, key []byte) error {
ciphertext, err := os.readfile(inputfile)
if err != nil {
return err
}
plaintext, err := decrypt(ciphertext, key)
if err != nil {
return err
}
return os.writefile(outputfile, plaintext, 0644)
}
func main() {
// summon a magical key
key := make([]byte, 32) // aes-256
if _, err := rand.read(key); err != nil {
panic("our magical key summoning failed!")
}
// cast our encryption spell
err := encryptfile("secret_scroll.txt", "encrypted_scroll.bin", key)
if err != nil {
panic("our encryption spell fizzled!")
}
fmt.println("scroll successfully enchanted with secrecy!")
// remove the encryption enchantment
err = decryptfile("encrypted_scroll.bin", "decrypted_scroll.txt", key)
if err != nil {
panic("our decryption counter-spell backfired!")
}
fmt.println("scroll successfully disenchanted!")
}
这个神奇的卷轴演示了使用 aes-gcm 的安全文件加密。它包括防止魔法事故(错误处理)、安全调用随机数的随机数以及适当的魔法密钥管理实践。
结界#2:pki 召唤仪式
现在,让我们执行一个更复杂的仪式来调用基本的公钥基础设施 (pki) 系统。该系统可以生成神奇的证书,用证书颁发机构(ca)对其进行签名,并验证这些神秘的文件。
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"os"
"time"
)
// Summon a magical key pair
func generateKey() (*ecdsa.PrivateKey, error) {
return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
}
// Create a mystical certificate
func createCertificate(template, parent *x509.Certificate, pub interface{}, priv interface{}) (*x509.Certificate, []byte, error) {
certDER, err := x509.CreateCertificate(rand.Reader, template, parent, pub, priv)
if err != nil {
return nil, nil, err
}
cert, err := x509.ParseCertificate(certDER)
if err != nil {
return nil, nil, err
}
return cert, certDER, nil
}
// Summon a Certificate Authority
func generateCA() (*x509.Certificate, *ecdsa.PrivateKey, error) {
caPrivKey, err := generateKey()
if err != nil {
return nil, nil, err
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{"Wizards' Council"},
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(10, 0, 0),
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
IsCA: true,
}
caCert, _, err := createCertificate(&template, &template, &caPrivKey.PublicKey, caPrivKey)
if err != nil {
return nil, nil, err
}
return caCert, caPrivKey, nil
}
// Generate a certificate for a magical domain
func generateCertificate(caCert *x509.Certificate, caPrivKey *ecdsa.PrivateKey, domain string) (*x509.Certificate, *ecdsa.PrivateKey, error) {
certPrivKey, err := generateKey()
if err != nil {
return nil, nil, err
}
template := x509.Certificate{
SerialNumber: big.NewInt(2),
Subject: pkix.Name{
Organization: []string{"Wizards' Guild"},
CommonName: domain,
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(1, 0, 0),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
DNSNames: []string{domain},
}
cert, _, err := createCertificate(&template, caCert, &certPrivKey.PublicKey, caPrivKey)
if err != nil {
return nil, nil, err
}
return cert, certPrivKey, nil
}
// Inscribe a certificate onto a magical parchment (PEM)
func saveCertificateToPEM(cert *x509.Certificate, filename string) error {
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
return os.WriteFile(filename, certPEM, 0644)
}
// Inscribe a private key onto a magical parchment (PEM)
func savePrivateKeyToPEM(privKey *ecdsa.PrivateKey, filename string) error {
privKeyBytes, err := x509.MarshalECPrivateKey(privKey)
if err != nil {
return err
}
privKeyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: privKeyBytes})
return os.WriteFile(filename, privKeyPEM, 0600)
}
func main() {
// Summon the Certificate Authority
caCert, caPrivKey, err := generateCA()
if err != nil {
panic("The CA summoning ritual failed!")
}
// Inscribe the CA certificate and private key
err = saveCertificateToPEM(caCert, "ca_cert.pem")
if err != nil {
panic("Failed to inscribe the CA certificate!")
}
err = savePrivateKeyToPEM(caPrivKey, "ca_key.pem")
if err != nil {
panic("Failed to inscribe the CA private key!")
}
// Generate a certificate for a magical domain
domain := "hogwarts.edu"
cert, privKey, err := generateCertificate(caCert, caPrivKey, domain)
if err != nil {
panic("The domain certificate summoning failed!")
}
// Inscribe the domain certificate and private key
err = saveCertificateToPEM(cert, "domain_cert.pem")
if err != nil {
panic("Failed to inscribe the domain certificate!")
}
err = savePrivateKeyToPEM(privKey, "domain_key.pem")
if err != nil {
panic("Failed to inscribe the domain private key!")
}
fmt.Println("The PKI summoning ritual was successful! CA and domain certificates have been manifested.")
}
这个神秘的仪式演示了一个简单的 pki 系统的创建,包括:
- 调用证书颁发机构 (ca)
- 使用 ca 为域证书加持其神奇的签名
- 将证书和私钥刻在神奇的羊皮纸上(pem 格式)
这些示例展示了 go 加密包的实际应用,演示了安全文件加密和基本的 pki 系统。它们融合了我们讨论过的许多最佳实践和概念,例如正确的密钥管理、安全随机数生成以及现代加密算法的使用。
请记住,年轻的巫师,在现实世界中实施这些加密系统时,请始终确保您的咒语经过其他大师巫师的彻底审查和测试。对于最关键的魔法组件,请尽可能考虑使用已建立的魔法书(库)。
现在就出去负责任地施展你的加密咒语吧!愿您的秘密始终保密,您的身份始终得到验证!
到这里,我们也就讲完了《现实世界的加密魔法:让 Go 的加密包发挥作用,Go Crypto 13》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
-
505 收藏
-
503 收藏
-
502 收藏
-
502 收藏
-
502 收藏
-
364 收藏
-
267 收藏
-
320 收藏
-
489 收藏
-
134 收藏
-
150 收藏
-
300 收藏
-
300 收藏
-
322 收藏
-
204 收藏
-
209 收藏
-
285 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习