搜尋
首頁後端開發Golang公鑰密碼學:數位握手,Go Crypto 5

Public-Key Cryptography: The Digital Handshake, Go Crypto 5

嘿,加密貨幣探索者!準備好進入公鑰密碼學的迷人世界了嗎?將其視為您可以在公共場合進行的秘密握手的數位形式。聽起來不可能?讓我們分解一下,看看 Go 如何幫助我們實現這個加密魔術!

RSA:公鑰加密貨幣的鼻祖

首先,我們有 RSA (Rivest-Shamir-Adleman)。它就像公鑰系統的睿智老祖父 - 已經存在了很多年並且仍然很強大。

RSA 金鑰產生:您的數位身份

讓我們從建立 RSA 金鑰開始:

import (
    "crypto/rand"
    "crypto/rsa"
    "fmt"
)

func main() {
    // Let's make a 2048-bit key. It's like choosing a really long password!
    privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
    if err != nil {
        panic("Oops! Our key generator is feeling shy today.")
    }

    publicKey := &privateKey.PublicKey

    fmt.Println("Tada! We've got our keys. Keep the private one secret!")
    fmt.Printf("Private Key: %v\n", privateKey)
    fmt.Printf("Public Key: %v\n", publicKey)
}

RSA加解密:傳遞密文

現在,讓我們使用這些金鑰來發送秘密訊息:

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/sha256"
    "fmt"
)

func main() {
    privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
    publicKey := &privateKey.PublicKey

    secretMessage := []byte("RSA is like a magic envelope!")

    // Encryption - Sealing our magic envelope
    ciphertext, err := rsa.EncryptOAEP(
        sha256.New(),
        rand.Reader,
        publicKey,
        secretMessage,
        nil,
    )
    if err != nil {
        panic("Our magic envelope got stuck!")
    }

    fmt.Printf("Our secret message, encrypted: %x\n", ciphertext)

    // Decryption - Opening our magic envelope
    plaintext, err := rsa.DecryptOAEP(
        sha256.New(),
        rand.Reader,
        privateKey,
        ciphertext,
        nil,
    )
    if err != nil {
        panic("Uh-oh, we can't open our own envelope!")
    }

    fmt.Printf("Decrypted message: %s\n", plaintext)
}

RSA 簽名與驗證:您的數位簽名

RSA 不僅適用於秘密訊息。它還可以創建數位簽名:

import (
    "crypto"
    "crypto/rand"
    "crypto/rsa"
    "crypto/sha256"
    "fmt"
)

func main() {
    privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
    publicKey := &privateKey.PublicKey

    message := []byte("I solemnly swear that I am up to no good.")
    hash := sha256.Sum256(message)

    // Signing - Like signing a digital contract
    signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hash[:])
    if err != nil {
        panic("Our digital pen ran out of ink!")
    }

    fmt.Printf("Our digital signature: %x\n", signature)

    // Verification - Checking if the signature is genuine
    err = rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, hash[:], signature)
    if err != nil {
        fmt.Println("Uh-oh, this signature looks fishy!")
    } else {
        fmt.Println("Signature checks out. Mischief managed!")
    }
}

橢圓曲線密碼學 (ECC):區塊鏈上的新星

現在,我們來談談 ECC。它就像 RSA 更酷、更有效率的表弟。它透過更小的金鑰提供類似的安全性,這對於行動和物聯網設備來說非常有用。

ECDSA 金鑰產生:您的橢圓身份

讓我們建立 ECC 金鑰:

import (
    "crypto/ecdsa"
    "crypto/elliptic"
    "crypto/rand"
    "fmt"
)

func main() {
    privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
    if err != nil {
        panic("Our elliptic curve generator took a wrong turn!")
    }

    publicKey := &privateKey.PublicKey

    fmt.Println("Voila! Our elliptic curve keys are ready.")
    fmt.Printf("Private Key: %v\n", privateKey)
    fmt.Printf("Public Key: %v\n", publicKey)
}

ECDSA 簽名與驗證:曲線簽名

現在,讓我們用橢圓鍵簽一些內容:

import (
    "crypto/ecdsa"
    "crypto/elliptic"
    "crypto/rand"
    "crypto/sha256"
    "fmt"
)

func main() {
    privateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
    publicKey := &privateKey.PublicKey

    message := []byte("Elliptic curves are mathematically delicious!")
    hash := sha256.Sum256(message)

    // Signing - Like signing with a very curvy pen
    r, s, err := ecdsa.Sign(rand.Reader, privateKey, hash[:])
    if err != nil {
        panic("Our curvy signature got a bit too curvy!")
    }

    fmt.Printf("Our elliptic signature: (r=%x, s=%x)\n", r, s)

    // Verification - Checking if our curvy signature is legit
    valid := ecdsa.Verify(publicKey, hash[:], r, s)
    fmt.Printf("Is our curvy signature valid? %v\n", valid)
}

金鑰管理:確保您的數位身分安全

現在,我們來談談如何確保這些金鑰的安全。這就像擁有一把非常重要的鑰匙,打開一扇非常重要的門 - 您希望確保它的安全!

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/pem"
    "fmt"
)

func main() {
    privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)

    // Encoding our private key - Like putting it in a special envelope
    privateKeyBytes := x509.MarshalPKCS1PrivateKey(privateKey)
    privateKeyPEM := pem.EncodeToMemory(&pem.Block{
        Type:  "RSA PRIVATE KEY",
        Bytes: privateKeyBytes,
    })

    fmt.Printf("Our key in its special envelope:\n%s\n", privateKeyPEM)

    // Decoding our private key - Taking it out of the envelope
    block, _ := pem.Decode(privateKeyPEM)
    decodedPrivateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    if err != nil {
        panic("We forgot how to open our own envelope!")
    }

    fmt.Printf("Our key, safe and sound: %v\n", decodedPrivateKey)
}

公鑰密碼學的黃金法則

既然您正在使用這些強大的加密工具,請記住以下一些黃金規則:

  1. 大小很重要:對於 RSA,要麼變大,要麼回家 - 至少 2048 位。對於 ECC,256 位元是最佳選擇。

  2. 隨機性是你的朋友:總是使用加密/隨機數字來產生金鑰。使用弱隨機性就像使用“password123”作為密鑰。

  3. 輪換您的密鑰:就像更改密碼一樣,定期輪換您的密鑰。

  4. 標準格式之所以成為標準是有原因的:使用 PEM 來儲存和發送金鑰。這就像使用標準信封 - 每個人都知道如何處理它。

  5. 填充不僅適用於家具:對於 RSA 加密,請始終使用 OAEP 填充。它就像是加密資料的氣泡包裝。

  6. 簽名前雜湊:簽署大數據時,對雜湊值進行簽名,而不是資料本身。它更快而且同樣安全。

  7. 效能很重要:公鑰操作可能很慢,尤其是 RSA。明智地使用它們。

接下來是什麼?

恭喜!您剛剛將公鑰加密新增到您的工具包。這些技術非常適合安全通訊、數位簽名以及在互聯網的狂野西部建立信任。

接下來,我們將深入研究數位簽章及其應用程式。這就像學習以一種無法偽造的方式寫下你的名字 - 很酷,對吧?

請記住,在密碼學領域,理解這些基礎知識至關重要。這就像在開始開車之前學習道路規則一樣。掌握這些,您將能夠順利地在 Go 中建立安全、強大的應用程式。

那麼,您嘗試使用朋友的公鑰為朋友加密訊息怎麼樣?或者也許實現一個簡單的數位簽章系統?安全、經過身份驗證的通訊世界觸手可及!快樂編碼,加密冠軍!

以上是公鑰密碼學:數位握手,Go Crypto 5的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Golang vs. Python:利弊Golang vs. Python:利弊Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang和C:並發與原始速度Golang和C:並發與原始速度Apr 21, 2025 am 12:16 AM

Golang在並發性上優於C ,而C 在原始速度上優於Golang。 1)Golang通過goroutine和channel實現高效並發,適合處理大量並發任務。 2)C 通過編譯器優化和標準庫,提供接近硬件的高性能,適合需要極致優化的應用。

為什麼要使用Golang?解釋的好處和優勢為什麼要使用Golang?解釋的好處和優勢Apr 21, 2025 am 12:15 AM

選擇Golang的原因包括:1)高並發性能,2)靜態類型系統,3)垃圾回收機制,4)豐富的標準庫和生態系統,這些特性使其成為開發高效、可靠軟件的理想選擇。

Golang vs.C:性能和速度比較Golang vs.C:性能和速度比較Apr 21, 2025 am 12:13 AM

Golang適合快速開發和並發場景,C 適用於需要極致性能和低級控制的場景。 1)Golang通過垃圾回收和並發機制提升性能,適合高並發Web服務開發。 2)C 通過手動內存管理和編譯器優化達到極致性能,適用於嵌入式系統開發。

golang比C快嗎?探索極限golang比C快嗎?探索極限Apr 20, 2025 am 12:19 AM

Golang在編譯時間和並發處理上表現更好,而C 在運行速度和內存管理上更具優勢。 1.Golang編譯速度快,適合快速開發。 2.C 運行速度快,適合性能關鍵應用。 3.Golang並發處理簡單高效,適用於並發編程。 4.C 手動內存管理提供更高性能,但增加開發複雜度。

Golang:從Web服務到系統編程Golang:從Web服務到系統編程Apr 20, 2025 am 12:18 AM

Golang在Web服務和系統編程中的應用主要體現在其簡潔、高效和並發性上。 1)在Web服務中,Golang通過強大的HTTP庫和並發處理能力,支持創建高性能的Web應用和API。 2)在系統編程中,Golang利用接近硬件的特性和對C語言的兼容性,適用於操作系統開發和嵌入式系統。

Golang vs.C:基準和現實世界的表演Golang vs.C:基準和現實世界的表演Apr 20, 2025 am 12:18 AM

Golang和C 在性能對比中各有優劣:1.Golang適合高並發和快速開發,但垃圾回收可能影響性能;2.C 提供更高性能和硬件控制,但開發複雜度高。選擇時需綜合考慮項目需求和團隊技能。

Golang vs. Python:比較分析Golang vs. Python:比較分析Apr 20, 2025 am 12:17 AM

Golang适合高性能和并发编程场景,Python适合快速开发和数据处理。1.Golang强调简洁和高效,适用于后端服务和微服务。2.Python以简洁语法和丰富库著称,适用于数据科学和机器学习。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器