」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Implementasi Metode 標準對稱加密簽章 pada Golang

Implementasi Metode 標準對稱加密簽章 pada Golang

發佈於2024-07-31
瀏覽:435

Image description

什麼是標準對稱加密簽章方法?

所以,你看,這種方法是一種加密資料的方法,這樣資料就安全了,沒有解密金鑰的人就無法讀取資料。想像一下,朋友們,你們有一本用掛鎖鎖住的日記。只有擁有鑰匙的人才能打開並閱讀你的日記。

對稱加密

對稱加密就像朋友和朋友,這是什麼,哈哈哈,重點是,就像擁有同一把鑰匙開鎖一樣。此密鑰用於加密(鎖定)和解密(解鎖)資料。所以,只要你有鑰匙,好友和好友都可以鎖定和解鎖相同的資料。

簽名

這裡的簽名不是實體簽名,而是數位簽名。這個簽名保證了發送的資料是真正來自朋友的,並且沒有人中途更改過資料。所以朋友們,您可以確定您收到的數據是來自源頭的真實數據,沒有被竄改。

為什麼要用這個方法?

  • 資料安全:您肯定希望您的資料免受惡意之手的侵害,對嗎?透過對稱加密,您的資料被加密,只有擁有金鑰的人才能開啟。
  • 資料完整性:透過簽名,您可以確保您接收或發送的資料是真實的且未被竄改。所以朋友們,你們不用擔心有人會作弊。
  • 效率:對稱加密通常比非對稱加密更快,因為加密和解密過程更簡單。

Golang 中的使用範例

現在讓我們看看如何在Golang中使用這個方法。

Golang 中的對稱加密

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "encoding/hex"
    "fmt"
    "io"
)

func encrypt(key, text []byte) (string, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return "", err
    }

    ciphertext := make([]byte, aes.BlockSize len(text))
    iv := ciphertext[:aes.BlockSize]
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        return "", err
    }

    stream := cipher.NewCFBEncrypter(block, iv)
    stream.XORKeyStream(ciphertext[aes.BlockSize:], text)

    return fmt.Sprintf("%x", ciphertext), nil
}

func decrypt(key []byte, cryptoText string) (string, error) {
    ciphertext, _ := hex.DecodeString(cryptoText)

    block, err := aes.NewCipher(key)
    if err != nil {
        return "", err
    }

    if len(ciphertext) 



簽名 Golang

package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "fmt"
)

func createHMAC(key, message []byte) string {
    mac := hmac.New(sha256.New, key)
    mac.Write(message)
    return hex.EncodeToString(mac.Sum(nil))
}

func verifyHMAC(key, message []byte, signature string) bool {
    expectedMAC := createHMAC(key, message)
    return hmac.Equal([]byte(expectedMAC), []byte(signature))
}

func main() {
    key := []byte("my-secret-key")
    message := []byte("important message")

    signature := createHMAC(key, message)
    fmt.Printf("Signature: %s\n", signature)

    isValid := verifyHMAC(key, message, signature)
    fmt.Printf("Is valid: %t\n", isValid)
}

因此,標準對稱加密簽章方法對於維護資料的安全性和完整性非常重要。透過對稱加密,您可以對資料進行加密以使其安全,而透過簽名,您可以確保您接收或發送的資料是真實的且未被篡改。所以,請確保朋友們在各種需要高安全性的需求時使用此方法。

來源:

  • HMAC Go
  • SHA256
版本聲明 本文轉載於:https://dev.to/yogameleniawan/implementasi-metode-standard-symmetric-encryption-signature-pada-golang-2m5m?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3