首頁  >  文章  >  後端開發  >  對稱加密:密碼學的秘密握手,Go Crypto 4

對稱加密:密碼學的秘密握手,Go Crypto 4

Patricia Arquette
Patricia Arquette原創
2024-10-20 06:07:30596瀏覽

Symmetric Encryption: The Secret Handshake of Cryptography, Go Crypto 4

嘿,加密貨幣愛好者!準備好進入對稱加密的世界了嗎?將其視為數位世界的秘密握手 - 兩方共享只有他們才能理解的資訊的方式。讓我們分解一下,看看 Go 如何幫助我們實現這些數字秘密握手!

分組密碼:建構塊

首先,我們有分組密碼。它們就像數位時代的密碼輪——它們處理固定大小的資料塊。這裡的明星是 AES(高級加密標準)。

AES:重量級冠軍

AES 就像加密領域的瑞士軍刀 - 它用途廣泛、功能強大且用途廣泛。以下是在 Go 中的設定方法:

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

func main() {
    // Let's create a 256-bit key (32 bytes)
    key := make([]byte, 32)
    if _, err := rand.Read(key); err != nil {
        panic("Oops, the universe's randomness machine broke!")
    }

    block, err := aes.NewCipher(key)
    if err != nil {
        panic("AES threw a tantrum!")
    }

    fmt.Printf("Our AES block size: %d bytes\n", block.BlockSize())
}

這設定了 AES,但請記住,單獨的分組密碼就像一輛沒有輪子的汽車 - 功能齊全,但還不是很有用。這就是操作模式的用武之地,但我們稍後會討論它。

流密碼:加密的流動之河

接下來,我們有流密碼。這些就像一個永無止境的隨機位元流,我們將其與資料進行異或以對其進行加密。 Go 為我們帶來了 ChaCha20,一種現代的、快速的流密碼。

ChaCha20:街區新來的孩子

以下是使用 ChaCha20 的方法:

import (
    "fmt"
    "golang.org/x/crypto/chacha20"
)

func main() {
    key := make([]byte, chacha20.KeySize)
    nonce := make([]byte, chacha20.NonceSize)

    cipher, err := chacha20.NewUnauthenticatedCipher(key, nonce)
    if err != nil {
        panic("ChaCha20 isn't feeling chatty today!")
    }

    secretMessage := []byte("ChaCha20 is my new dance move!")
    encrypted := make([]byte, len(secretMessage))
    cipher.XORKeyStream(encrypted, secretMessage)

    fmt.Printf("Our secret dance move, encrypted: %x\n", encrypted)
}

當您需要速度時,ChaCha20 非常有用,尤其是在沒有 AES 硬體加速的平台上。

運作模式:將它們放在一起

現在我們來談談操作方式。這些就像遊戲規則 - 它們定義了我們如何使用密碼安全地加密資料。

GCM(伽羅瓦/計數器模式):瑞士軍刀

GCM 就像是加密模式中的瑞士軍刀。它提供保密性和完整性,這就是為什麼在大多數用例中強烈推薦它。使用方法如下:

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "fmt"
)

func main() {
    key := make([]byte, 32)
    if _, err := rand.Read(key); err != nil {
        panic("The random number generator went on strike!")
    }

    block, err := aes.NewCipher(key)
    if err != nil {
        panic("AES is having an existential crisis!")
    }

    nonce := make([]byte, 12)
    if _, err := rand.Read(nonce); err != nil {
        panic("Nonce generator is feeling noncommittal!")
    }

    aesgcm, err := cipher.NewGCM(block)
    if err != nil {
        panic("GCM mode is feeling moody!")
    }

    secretMessage := []byte("AES-GCM: Making encryption great again!")
    encrypted := aesgcm.Seal(nil, nonce, secretMessage, nil)

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

    // Let's decrypt it to make sure it worked
    decrypted, err := aesgcm.Open(nil, nonce, encrypted, nil)
    if err != nil {
        panic("Decryption failed! Did someone tamper with our message?")
    }

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

CTR(計數器模式):Streamifier

CTR 模式就像一根魔杖,可以將分組密碼變成流密碼。當您需要流密碼的靈活性但又想堅持使用分組密碼演算法時,它非常有用:

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "fmt"
)

func main() {
    key := make([]byte, 32)
    if _, err := rand.Read(key); err != nil {
        panic("Random number generator is feeling random about its job!")
    }

    block, err := aes.NewCipher(key)
    if err != nil {
        panic("AES is having a block party, and we're not invited!")
    }

    iv := make([]byte, aes.BlockSize)
    if _, err := rand.Read(iv); err != nil {
        panic("IV generator is feeling too independent!")
    }

    stream := cipher.NewCTR(block, iv)

    secretMessage := []byte("CTR mode: Turning blocks into streams since 1979!")
    encrypted := make([]byte, len(secretMessage))
    stream.XORKeyStream(encrypted, secretMessage)

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

    // Let's decrypt it
    decrypted := make([]byte, len(encrypted))
    stream = cipher.NewCTR(block, iv) // Reset the stream
    stream.XORKeyStream(decrypted, encrypted)

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

對稱加密的黃金法則

現在您已經擁有了這些閃亮的新加密工具,請記住以下一些黃金規則:

  1. GCM 是你的朋友:大多數情況下,使用 AES-GCM。它就像您資料的保鑣 - 它既保護機密性又保證完整性。

  2. 隨機數是生活的調味品:每次加密操作總是使用唯一的隨機數(使用過一次的數字)。它就像每個秘密訊息的唯一識別碼。

  3. 隨機性是關鍵:使用加密/隨機產生金鑰。使用弱密鑰就像在您的銀行帳戶中使用“password123”一樣。

  4. CTR 需要一個夥伴:如果您使用 CTR 模式,請記住它不能保護完整性。如果您需要完整性保護,請考慮將其與 MAC 配對。

  5. 錯誤處理不是可選的:始終處理錯誤,尤其是在金鑰產生和初始化期間。忽略加密代碼中的錯誤就像忽略汽車上的“檢查引擎”燈一樣。

  6. 保守你的秘密:永遠不要在原始碼中硬編碼密鑰。這就像把你家的鑰匙藏在迎賓墊下 - 攻擊者首先會看到的地方!

接下來是什麼?

恭喜!您剛剛將對稱加密新增到您的加密工具包中。當雙方共享金鑰時,這些技術非常適合保護資料。

但是如果您需要與以前從未見過的人建立安全連線怎麼辦?這就是公鑰密碼學的用武之地,我們將在下一節中探討它。這就像秘密握手和公開簽名之間的區別 - 兩者都很有用,但適用於不同的場景。

請記住,在密碼學領域,理解這些基礎知識至關重要。這就像在建造城堡之前學會鎖門一樣。掌握這些,您將能夠順利地在 Go 中建立安全、強大的應用程式。

那麼,您嘗試加密給自己的訊息怎麼樣?或者也許使用 AES-GCM 實現一個簡單的安全筆記應用程式?安全通訊的世界觸手可及!快樂編碼,加密冠軍!

以上是對稱加密:密碼學的秘密握手,Go Crypto 4的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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