• <strike id="6sogq"><s id="6sogq"></s></strike>
  • <strike id="6sogq"></strike>

    千鋒教育-做有情懷、有良心、有品質(zhì)的職業(yè)教育機(jī)構(gòu)

    400-811-9990
    手機(jī)站
    千鋒教育

    千鋒學(xué)習(xí)站 | 隨時(shí)隨地免費(fèi)學(xué)

    千鋒教育

    掃一掃進(jìn)入千鋒手機(jī)站

    領(lǐng)取全套視頻
    千鋒教育

    關(guān)注千鋒學(xué)習(xí)站小程序
    隨時(shí)隨地免費(fèi)學(xué)習(xí)課程

    上海
    • 北京
    • 鄭州
    • 武漢
    • 成都
    • 西安
    • 沈陽
    • 廣州
    • 南京
    • 深圳
    • 大連
    • 青島
    • 杭州
    • 重慶
    當(dāng)前位置:成都千鋒IT培訓(xùn)  >  技術(shù)干貨  >  Golang中的加密與解密實(shí)踐

    Golang中的加密與解密實(shí)踐

    來源:千鋒教育
    發(fā)布人:xqq
    時(shí)間: 2023-12-27 21:27:18

    Golang中的加密與解密實(shí)踐

    隨著互聯(lián)網(wǎng)的不斷發(fā)展,越來越多的信息需要傳輸,而這些信息中很多都是敏感信息,為了保證信息安全,加密技術(shù)就被廣泛應(yīng)用。在Golang中,我們可以通過各種加密算法來保證信息安全,同時(shí)也可以通過相應(yīng)的解密算法來還原加密后的信息。本文將介紹一些常見的加密與解密算法,并提供相應(yīng)的代碼示例。

    一、MD5加密算法

    MD5是一種哈希算法,它將任意長度的二進(jìn)制值映射為一個(gè)128位的小寫字母和數(shù)字組成的字符串。MD5算法具有抗碰撞特性,即不同的輸入得到的哈希值很難相同。在Golang中,我們可以通過crypto/md5包來實(shí)現(xiàn)MD5加密算法。

    示例代碼:

    `go

    import (

    "crypto/md5"

    "encoding/hex"

    "fmt"

    )

    // 對字符串進(jìn)行MD5加密

    func Md5Encrypt(str string) string {

    md5Ctx := md5.New()

    md5Ctx.Write(byte(str))

    cipherStr := md5Ctx.Sum(nil)

    return hex.EncodeToString(cipherStr)

    }

    func main() {

    str := "hello world"

    encryptedStr := Md5Encrypt(str)

    fmt.Println("加密前:", str)

    fmt.Println("加密后:", encryptedStr)

    }

    二、AES加密算法AES是一種對稱加密算法,它是目前最流行的加密算法之一,具有高效、安全、可靠等特點(diǎn)。在Golang中,我們可以通過crypto/aes包來實(shí)現(xiàn)AES加密算法。示例代碼:`goimport (    "bytes"    "crypto/aes"    "crypto/cipher"    "encoding/base64"    "fmt") // 對字符串進(jìn)行AES加密func AesEncrypt(str, key string) (string, error) {    strBytes := byte(str)    keyBytes := byte(key)     block, err := aes.NewCipher(keyBytes)    if err != nil {        return "", err    }     blockSize := block.BlockSize()    strBytes = PKCS5Padding(strBytes, blockSize)     iv := keyBytes     blockMode := cipher.NewCBCEncrypter(block, iv)    cipherText := make(byte, len(strBytes))    blockMode.CryptBlocks(cipherText, strBytes)     return base64.StdEncoding.EncodeToString(cipherText), nil} // 對字符串進(jìn)行AES解密func AesDecrypt(str, key string) (string, error) {    strBytes, err := base64.StdEncoding.DecodeString(str)    if err != nil {        return "", err    }    keyBytes := byte(key)     block, err := aes.NewCipher(keyBytes)    if err != nil {        return "", err    }     blockSize := block.BlockSize()     iv := keyBytes     blockMode := cipher.NewCBCDecrypter(block, iv)    origData := make(byte, len(strBytes))     blockMode.CryptBlocks(origData, strBytes)    origData = PKCS5UnPadding(origData)     return string(origData), nil} // PKCS5填充func PKCS5Padding(cipherText byte, blockSize int) byte {    padding := blockSize - len(cipherText)%blockSize    padText := bytes.Repeat(byte{byte(padding)}, padding)    return append(cipherText, padText...)} // PKCS5去除填充func PKCS5UnPadding(origData byte) byte {    length := len(origData)    unPadding := int(origData)    return origData} func main() {    str := "hello world"    key := "1234567890123456"     encryptedStr, err := AesEncrypt(str, key)    if err != nil {        fmt.Println("加密失敗:", err)        return    }     decryptedStr, err := AesDecrypt(encryptedStr, key)    if err != nil {        fmt.Println("解密失敗:", err)        return    }     fmt.Println("加密前:", str)    fmt.Println("加密后:", encryptedStr)    fmt.Println("解密后:", decryptedStr)}

    三、RSA加密算法

    RSA是一種非對稱加密算法,它通過公鑰加密、私鑰解密的方式實(shí)現(xiàn)信息的安全傳輸。在Golang中,我們可以通過crypto/rsa包來實(shí)現(xiàn)RSA加密算法。

    示例代碼:

    `go

    import (

    "crypto/rand"

    "crypto/rsa"

    "crypto/x509"

    "encoding/base64"

    "encoding/pem"

    "fmt"

    )

    // 生成RSA密鑰對

    func GenerateRsaKeyPair() (*rsa.PrivateKey, error) {

    privateKey, err := rsa.GenerateKey(rand.Reader, 2048)

    if err != nil {

    return nil, err

    }

    return privateKey, nil

    }

    // 使用公鑰進(jìn)行RSA加密

    func RsaEncrypt(plainText byte, publicKey byte) (byte, error) {

    block, _ := pem.Decode(publicKey)

    if block == nil {

    return nil, fmt.Errorf("public key error")

    }

    pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)

    if err != nil {

    return nil, err

    }

    pub := pubInterface.(*rsa.PublicKey)

    cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, pub, plainText)

    if err != nil {

    return nil, err

    }

    return cipherText, nil

    }

    // 使用私鑰進(jìn)行RSA解密

    func RsaDecrypt(cipherText byte, privateKey byte) (byte, error) {

    block, _ := pem.Decode(privateKey)

    if block == nil {

    return nil, fmt.Errorf("private key error")

    }

    priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)

    if err != nil {

    return nil, err

    }

    plainText, err := rsa.DecryptPKCS1v15(rand.Reader, priv, cipherText)

    if err != nil {

    return nil, err

    }

    return plainText, nil

    }

    func main() {

    str := "hello world"

    privateKey, err := GenerateRsaKeyPair()

    if err != nil {

    fmt.Println("生成密鑰對失敗:", err)

    return

    }

    publicKey := &privateKey.PublicKey

    cipherText, err := RsaEncrypt(byte(str), byte(publicKey))

    if err != nil {

    fmt.Println("加密失敗:", err)

    return

    }

    plainText, err := RsaDecrypt(cipherText, byte(privateKey))

    if err != nil {

    fmt.Println("解密失敗:", err)

    return

    }

    fmt.Println("加密前:", str)

    fmt.Println("加密后:", base64.StdEncoding.EncodeToString(cipherText))

    fmt.Println("解密后:", string(plainText))

    }

    四、總結(jié)

    本文介紹了Golang中常見的加密與解密算法,包括MD5、AES、RSA等。這些加密算法在實(shí)際開發(fā)中非常常見,開發(fā)者需要在保證信息安全的前提下,選擇合適的加密算法來保護(hù)數(shù)據(jù)的安全。同時(shí),本文提供了相應(yīng)的代碼示例,讀者可以根據(jù)需要進(jìn)行調(diào)整和使用。

    聲明:本站稿件版權(quán)均屬千鋒教育所有,未經(jīng)許可不得擅自轉(zhuǎn)載。

    猜你喜歡LIKE

    Golang中的加密與解密實(shí)踐

    2023-12-27

    如何使用Docker進(jìn)行部署?

    2023-12-27

    13無縫集成GoModules

    2023-12-27

    最新文章NEW

    7個(gè)提升golang性能的技巧

    2023-12-27

    GoLand實(shí)現(xiàn)高效的代碼完成

    2023-12-27

    Go語言中的內(nèi)存管理和垃圾回收

    2023-12-27

    相關(guān)推薦HOT

    更多>>

    快速通道 更多>>

    最新開班信息 更多>>

    網(wǎng)友熱搜 更多>>