因在做license注冊(cè)機(jī)制當(dāng)中,有對(duì)根據(jù)本地RSA pem密鑰文件判斷出RSA的公私密鑰長(zhǎng)度的需求(即:根據(jù)pem內(nèi)容判斷出RSA密鑰是1024位或者2048位,或者其他位數(shù)等),因此個(gè)人通過(guò)思考,摸索整理出一個(gè)方法,予以記錄,備用,分享。
package main
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"os"
)
//全局變量
var privateKey, publicKey []byte
func init() {
var err error
publicKey, err = ioutil.ReadFile("public.pem")
if err != nil {
os.Exit(-1)
}
privateKey, err = ioutil.ReadFile("private.pem")
if err != nil {
os.Exit(-1)
}
}
/**
* @brief 獲取RSA公鑰長(zhǎng)度
* @param[in] PubKey RSA公鑰
* @return 成功返回 RSA公鑰長(zhǎng)度,失敗返回error 錯(cuò)誤信息
*/
func GetPubKeyLen(PubKey []byte) (int, error) {
if PubKey == nil {
return 0, errors.New("input arguments error")
}
block, _ := pem.Decode(PubKey)
if block == nil {
return 0, errors.New("public rsaKey error")
}
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return 0, err
}
pub := pubInterface.(*rsa.PublicKey)
return pub.N.BitLen(), nil
}
/**
* @brief 獲取RSA私鑰長(zhǎng)度
* @param[in] PriKey RSA私鑰
* @return 成功返回 RSA私鑰長(zhǎng)度,失敗返回error 錯(cuò)誤信息
*/
func GetPriKeyLen(PriKey []byte) (int, error) {
if PriKey == nil {
return 0, errors.New("input arguments error")
}
block, _ := pem.Decode(PriKey)
if block == nil {
return 0, errors.New("private rsaKey error!")
}
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return 0, err
}
return priv.N.BitLen(), nil
}
func main() {
//獲取rsa 公鑰長(zhǎng)度
PubKeyLen, _ := GetPubKeyLen(publicKey)
fmt.Println("pbulic key len is ", PubKeyLen)
//獲取rsa 私鑰長(zhǎng)度
PriKeyLen, _ := GetPriKeyLen(privateKey)
fmt.Println("private key len is ", PriKeyLen)
}
附錄:以下程序是產(chǎn)生RSA公私密鑰的程序,附件,方便測(cè)試。
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"flag"
"log"
"os"
)
func main() {
var bits int
flag.IntVar(bits, "b", 1024, "密鑰長(zhǎng)度,默認(rèn)為1024位")
flag.Parse()
if err := GenRsaKey(bits); err != nil {
log.Fatal("密鑰文件生成失??!")
}
log.Println("密鑰文件生成成功!")
}
func GenRsaKey(bits int) error {
// 生成私鑰文件
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return err
}
derStream := x509.MarshalPKCS1PrivateKey(privateKey)
block := pem.Block{
Type: "私鑰",
Bytes: derStream,
}
file, err := os.Create("private.pem")
if err != nil {
return err
}
err = pem.Encode(file, block)
if err != nil {
return err
}
// 生成公鑰文件
publicKey := privateKey.PublicKey
derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return err
}
block = pem.Block{
Type: "公鑰",
Bytes: derPkix,
}
file, err = os.Create("public.pem")
if err != nil {
return err
}
err = pem.Encode(file, block)
if err != nil {
return err
}
return nil
}
補(bǔ)充:golang 使用RSA生成公私鑰,加密,解密,并使用SHA256進(jìn)行簽名,驗(yàn)證
話不多說(shuō)直接上代碼:
package main
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"errors"
"fmt"
)
func main() {
//rsa 密鑰文件產(chǎn)生
fmt.Println("-------------------------------獲取RSA公私鑰-----------------------------------------")
prvKey, pubKey := GenRsaKey()
fmt.Println(string(prvKey))
fmt.Println(string(pubKey))
fmt.Println("-------------------------------進(jìn)行簽名與驗(yàn)證操作-----------------------------------------")
var data = "臥了個(gè)槽,這么神奇的嗎??!!! ԅ(¯﹃¯ԅ) ?。。。。。。?
fmt.Println("對(duì)消息進(jìn)行簽名操作...")
signData := RsaSignWithSha256([]byte(data), prvKey)
fmt.Println("消息的簽名信息: ", hex.EncodeToString(signData))
fmt.Println("\n對(duì)簽名信息進(jìn)行驗(yàn)證...")
if RsaVerySignWithSha256([]byte(data), signData, pubKey) {
fmt.Println("簽名信息驗(yàn)證成功,確定是正確私鑰簽名??!")
}
fmt.Println("-------------------------------進(jìn)行加密解密操作-----------------------------------------")
ciphertext := RsaEncrypt([]byte(data), pubKey)
fmt.Println("公鑰加密后的數(shù)據(jù):", hex.EncodeToString(ciphertext))
sourceData := RsaDecrypt(ciphertext, prvKey)
fmt.Println("私鑰解密后的數(shù)據(jù):", string(sourceData))
}
//RSA公鑰私鑰產(chǎn)生
func GenRsaKey() (prvkey, pubkey []byte) {
// 生成私鑰文件
privateKey, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
panic(err)
}
derStream := x509.MarshalPKCS1PrivateKey(privateKey)
block := pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: derStream,
}
prvkey = pem.EncodeToMemory(block)
publicKey := privateKey.PublicKey
derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
panic(err)
}
block = pem.Block{
Type: "PUBLIC KEY",
Bytes: derPkix,
}
pubkey = pem.EncodeToMemory(block)
return
}
//簽名
func RsaSignWithSha256(data []byte, keyBytes []byte) []byte {
h := sha256.New()
h.Write(data)
hashed := h.Sum(nil)
block, _ := pem.Decode(keyBytes)
if block == nil {
panic(errors.New("private key error"))
}
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
fmt.Println("ParsePKCS8PrivateKey err", err)
panic(err)
}
signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashed)
if err != nil {
fmt.Printf("Error from signing: %s\n", err)
panic(err)
}
return signature
}
//驗(yàn)證
func RsaVerySignWithSha256(data, signData, keyBytes []byte) bool {
block, _ := pem.Decode(keyBytes)
if block == nil {
panic(errors.New("public key error"))
}
pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
panic(err)
}
hashed := sha256.Sum256(data)
err = rsa.VerifyPKCS1v15(pubKey.(*rsa.PublicKey), crypto.SHA256, hashed[:], signData)
if err != nil {
panic(err)
}
return true
}
// 公鑰加密
func RsaEncrypt(data, keyBytes []byte) []byte {
//解密pem格式的公鑰
block, _ := pem.Decode(keyBytes)
if block == nil {
panic(errors.New("public key error"))
}
// 解析公鑰
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
panic(err)
}
// 類型斷言
pub := pubInterface.(*rsa.PublicKey)
//加密
ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, pub, data)
if err != nil {
panic(err)
}
return ciphertext
}
// 私鑰解密
func RsaDecrypt(ciphertext, keyBytes []byte) []byte {
//獲取私鑰
block, _ := pem.Decode(keyBytes)
if block == nil {
panic(errors.New("private key error!"))
}
//解析PKCS1格式的私鑰
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
panic(err)
}
// 解密
data, err := rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
if err != nil {
panic(err)
}
return data
}
運(yùn)行結(jié)果:
-------------------------------獲取RSA公私鑰-----------------------------------------
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCgPwlGJrWqTYaoMkI8jXkEI8ewQ7E57G2Fi91WTXMMK7X6GsT9
VmnRcq++Rk/VS+4IPBlfWyVRg0NfQDyuKjed21fUPa9AIbpYWHgP/tojyeYC1+Ra
Xncrt9kLp7nW4FZMJmzwU9hfxIB0nhDQqhJenjdBZuYZfkICfMqyqbVkAwIDAQAB
AoGAJRcSDXOuPrHdBhdD74ILTaL+eFTis3Z+zxdVbsFUbK+9WhtSFxUmPv1dohvi
JIuDl9JZSRHurFRGhsh2gxVwc7JXwWfD0DmD8dvdzr8q85Jml9YVZ7uhHFqSO4cY
I7dlBOd7Uwjnc39E/d+1E/kWVNfKt7opPHgt02zOHLSxkbECQQDS7H3myu3oLOi0
Slpd1MmmHVOo2cqJ1b3H6E8JtEjmHGswWTYvQNAe4yZ+Kffsp5LUYujedncPKvEj
4G+iz44bAkEAwn4Bx30FKTri/tybgSnCWKwTGSX479829Xucrm5pYU/3D5/PeJQL
Ra4YSyg2/hU3ZBrue6CdzYJgGXNGEWhAOQJBALMlOB4A96X+FruidzRA2fBj8j10
lakSSHl1H0RfwpbnRkcvTm0+AEZrqbL4lGGFRplrVNw2BBN25o8RPeArp0cCQEhu
kw0PI1fqhVUzJXqh6a4KT4aDHMWAlMAxi/VuSzKhjDo2Yxbd06DcqFF9JZXUou9W
FFDYTUyW7GEuC/85mwkCQCOEjUQX0C3JCSr6fyZIjpEr+znyc9eFHyBp+533Ur4g
eFu2ewJ3ufJiUBmEj1rEQku8W7h9DS2rXl10IiSwUAA=
-----END RSA PRIVATE KEY-----
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCgPwlGJrWqTYaoMkI8jXkEI8ew
Q7E57G2Fi91WTXMMK7X6GsT9VmnRcq++Rk/VS+4IPBlfWyVRg0NfQDyuKjed21fU
Pa9AIbpYWHgP/tojyeYC1+RaXncrt9kLp7nW4FZMJmzwU9hfxIB0nhDQqhJenjdB
ZuYZfkICfMqyqbVkAwIDAQAB
-----END PUBLIC KEY-----
-------------------------------進(jìn)行簽名與驗(yàn)證操作-----------------------------------------
對(duì)消息進(jìn)行簽名操作...
消息的簽名信息: 24a29efbc27e7b84c3b0eed683af28915381b2a0312f5383143cd2006b804d3a16c2b4750fb1857445b46664b795b6cefd402c5cf25e0f28116b7b50f5c16e80af9f9481def0161c6dac7a5d05c56595b891d84091e444ef4012ba1a0efd5cd2ff17c6dfdc109a2a3349ae2523217706a03042ea16d84fcf7d3dae37ee36d2e8
對(duì)簽名信息進(jìn)行驗(yàn)證...
簽名信息驗(yàn)證成功,確定是正確私鑰簽名??!
-------------------------------進(jìn)行加密解密操作-----------------------------------------
公鑰加密后的數(shù)據(jù): 2b34d46a62317f4f5e5c8618671831c0970cef2eeddc0d3aca02e1d5b411a067844e1250a1f69cbb1cbcb0cb1964af85836faa346f9ce9fac2710d4fa18e49ee1c4c73496183952fa95a54dd2d633b115504f0a365bac6d022399059a53f51c474e5e4f0f8eefde61bb85d5d812b67114f5d419c33496acaf11d3d84828733f7
私鑰解密后的數(shù)據(jù): 臥了個(gè)槽,這么神奇的嗎???。?! ԅ(¯﹃¯ԅ) ?。。。。。。?
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- Go 語(yǔ)言中g(shù)in使用gzip壓縮遇到的問(wèn)題
- go判斷文件夾是否存在并創(chuàng)建的實(shí)例
- go 協(xié)程返回值處理操作
- golang實(shí)現(xiàn)的文件上傳下載小工具
- Golang 實(shí)現(xiàn)復(fù)制文件夾同時(shí)復(fù)制文件
- golang文件讀取-按指定BUFF大小讀取方式
- 使用go讀取gzip格式的壓縮包的操作