博客 / 詳情

返回

Go語言中實現RSA加解密、簽名驗證算法

隨着互聯網的高速發展,人們對安全的要求也越來越高。密碼學中兩大經典算法,一個是對稱加解密,另一個是非對稱加解密,這裏就來分享一下非對稱加密算法的代表:RSA加解密。

在Go語言中實現RSA加解密還是比較簡單的,網上很多教程都是基於Go原生標準庫寫的,代碼量較多。這裏分享一個好用的庫:https://github.com/forgoer/openssl 。

安裝

go get https://github.com/forgoer/openssl

秘鑰生成

秘鑰可以生成在文件裏,也是生成到Buffer裏,只要實現了io.Writer即可。

import (
    "io/ioutil"
    "os"

    "github.com/forgoer/openssl"
)

func main() {

    // 創建私鑰文件
    priFile, err := os.Create("private.key") // 也可以使用buffer, priBuf := bytes.NewBuffer(nil)
    if err != nil {
        panic(err)
    }
    defer priFile.Close()
    // 生成私鑰到文件
    _ = openssl.RSAGenerateKey(1024, priFile)

    // 創建公鑰文件
    pubFile, err := os.Create("public.key")
    if err != nil {
        panic(err)
    }
    defer priFile.Close()

    // 通過私鑰生成公鑰到文件
    priByte, _ := ioutil.ReadFile("private.key")
    _ = openssl.RSAGeneratePublicKey(priByte, pubFile)
}

加解密

使用公鑰加密,私鑰解密。

    src := []byte("123456")
    pubByte, _ := ioutil.ReadFile("public.key")
    // 公鑰加密
    dst, _ := openssl.RSAEncrypt(src, pubByte)


    priByte, _ := ioutil.ReadFile("private.key")
    // 私鑰解密
    res, _ := openssl.RSADecrypt(dst, priByte)


    fmt.Println(string(res)) // 123456

簽名及驗證

使用私鑰簽名,公鑰驗證。

    // 私鑰簽名
    sign, err := openssl.RSASign([]byte("123456"), priByte, crypto.SHA256)
    if err != nil {
        panic(err)
    }

    // 公鑰驗證簽名
    err = openssl.RSAVerify([]byte("123456"), sign, pubByte, crypto.SHA256)
    if err != nil {
        panic(err)
    }

這個加解密庫:https://github.com/forgoer/openssl,它還支持AESDESRSAsha1Hmac-Sha1sha256Hmac-Sha256等常用算法。

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.