現実世界の暗号マジック: Go の暗号パッケージを機能させる、Go Crypto 13
こんにちは、暗号魔術師! Go の暗号パッケージを使って現実世界の魔法を体験してみませんか?これらのクールな暗号呪文をすべて学びました。今度はそれらをいくつかの実用的なエンチャントで使用してみましょう!安全なファイル暗号化の呪文と公開鍵基盤 (PKI) の召喚儀式という 2 つの強力なアーティファクトを作成します。
エンチャント #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の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











Golangは、パフォーマンスとスケーラビリティの点でPythonよりも優れています。 1)Golangのコンピレーションタイプの特性と効率的な並行性モデルにより、高い並行性シナリオでうまく機能します。 2)Pythonは解釈された言語として、ゆっくりと実行されますが、Cythonなどのツールを介してパフォーマンスを最適化できます。

Golangは並行性がCよりも優れていますが、Cは生の速度ではGolangよりも優れています。 1)Golangは、GoroutineとChannelを通じて効率的な並行性を達成します。これは、多数の同時タスクの処理に適しています。 2)Cコンパイラの最適化と標準ライブラリを介して、極端な最適化を必要とするアプリケーションに適したハードウェアに近い高性能を提供します。

Golangは迅速な発展と同時シナリオに適しており、Cは極端なパフォーマンスと低レベルの制御が必要なシナリオに適しています。 1)Golangは、ごみ収集と並行機関のメカニズムを通じてパフォーマンスを向上させ、高配列Webサービス開発に適しています。 2)Cは、手動のメモリ管理とコンパイラの最適化を通じて究極のパフォーマンスを実現し、埋め込みシステム開発に適しています。

speed、効率、およびシンプル性をspeedsped.1)speed:gocompilesquilesquicklyandrunseffictient、理想的なlargeprojects.2)効率:等系dribribraryreducesexexternaldedenciess、開発効果を高める3)シンプルさ:

goisidealforforbeginnersandsutable forcloudnetworkservicesduetoitssimplicity、andconcurrencyfeatures.1)installgofromtheofficialwebsiteandverify with'goversion'.2)

GolangとPythonにはそれぞれ独自の利点があります。Golangは高性能と同時プログラミングに適していますが、PythonはデータサイエンスとWeb開発に適しています。 Golangは同時性モデルと効率的なパフォーマンスで知られていますが、Pythonは簡潔な構文とリッチライブラリエコシステムで知られています。

Cは、ハードウェアリソースと高性能の最適化が必要なシナリオにより適していますが、Golangは迅速な開発と高い並行性処理が必要なシナリオにより適しています。 1.Cの利点は、ハードウェア特性と高い最適化機能に近いものにあります。これは、ゲーム開発などの高性能ニーズに適しています。 2.Golangの利点は、その簡潔な構文と自然な並行性サポートにあり、これは高い並行性サービス開発に適しています。

GolangとCのパフォーマンスの違いは、主にメモリ管理、コンピレーションの最適化、ランタイム効率に反映されています。 1)Golangのゴミ収集メカニズムは便利ですが、パフォーマンスに影響を与える可能性があります。
