golang 如何獲取pem格式RSA公私鑰長度

因在做license註冊機制當中,有對根據本地RSA pem密鑰文件判斷出RSA的公私密鑰長度的需求(即:根據pem內容判斷出RSA密鑰是1024位或者2048位,或者其他位數等),因此個人通過思考,摸索整理出一個方法,予以記錄,備用,分享。

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公鑰長度
 * @param[in]    PubKey				  RSA公鑰
 * @return  成功返回 RSA公鑰長度,失敗返回error	錯誤信息
 */
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私鑰長度
 * @param[in]    PriKey				  RSA私鑰
 * @return  成功返回 RSA私鑰長度,失敗返回error	錯誤信息
 */
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 公鑰長度
	PubKeyLen, _ := GetPubKeyLen(publicKey)
	fmt.Println("pbulic key len is ", PubKeyLen)
	//獲取rsa 私鑰長度
	PriKeyLen, _ := GetPriKeyLen(privateKey)
	fmt.Println("private key len is ", PriKeyLen)
}

附錄:以下程序是產生RSA公私密鑰的程序,附件,方便測試。

package main
import (
 "crypto/rand"
 "crypto/rsa"
 "crypto/x509"
 "encoding/pem"
 "flag"
 "log"
 "os"
)
func main() {
 var bits int
 flag.IntVar(&bits, "b", 1024, "密鑰長度,默認為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
}

補充:golang 使用RSA生成公私鑰,加密,解密,並使用SHA256進行簽名,驗證

話不多說直接上代碼:

package main
import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/hex"
	"encoding/pem"
	"errors"
	"fmt"
)
func main() {
	//rsa 密鑰文件產生
	fmt.Println("-------------------------------獲取RSA公私鑰-----------------------------------------")
	prvKey, pubKey := GenRsaKey()
	fmt.Println(string(prvKey))
	fmt.Println(string(pubKey))
	fmt.Println("-------------------------------進行簽名與驗證操作-----------------------------------------")
	var data = "臥瞭個槽,這麼神奇的嗎??!!! ԅ(¯﹃¯ԅ) !!!!!!)"
	fmt.Println("對消息進行簽名操作...")
	signData := RsaSignWithSha256([]byte(data), prvKey)
	fmt.Println("消息的簽名信息: ", hex.EncodeToString(signData))
	fmt.Println("\n對簽名信息進行驗證...")
	if RsaVerySignWithSha256([]byte(data), signData, pubKey) {
		fmt.Println("簽名信息驗證成功,確定是正確私鑰簽名!!")
	}
	fmt.Println("-------------------------------進行加密解密操作-----------------------------------------")
	ciphertext := RsaEncrypt([]byte(data), pubKey)
	fmt.Println("公鑰加密後的數據:", hex.EncodeToString(ciphertext))
	sourceData := RsaDecrypt(ciphertext, prvKey)
	fmt.Println("私鑰解密後的數據:", string(sourceData))
}
//RSA公鑰私鑰產生
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
}
//驗證
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
}

運行結果:

-------------------------------獲取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-----
-------------------------------進行簽名與驗證操作-----------------------------------------
對消息進行簽名操作...
消息的簽名信息: 24a29efbc27e7b84c3b0eed683af28915381b2a0312f5383143cd2006b804d3a16c2b4750fb1857445b46664b795b6cefd402c5cf25e0f28116b7b50f5c16e80af9f9481def0161c6dac7a5d05c56595b891d84091e444ef4012ba1a0efd5cd2ff17c6dfdc109a2a3349ae2523217706a03042ea16d84fcf7d3dae37ee36d2e8
對簽名信息進行驗證...
簽名信息驗證成功,確定是正確私鑰簽名!!
-------------------------------進行加密解密操作-----------------------------------------
公鑰加密後的數據: 2b34d46a62317f4f5e5c8618671831c0970cef2eeddc0d3aca02e1d5b411a067844e1250a1f69cbb1cbcb0cb1964af85836faa346f9ce9fac2710d4fa18e49ee1c4c73496183952fa95a54dd2d633b115504f0a365bac6d022399059a53f51c474e5e4f0f8eefde61bb85d5d812b67114f5d419c33496acaf11d3d84828733f7
私鑰解密後的數據: 臥瞭個槽,這麼神奇的嗎??!!! ԅ(¯﹃¯ԅ) !!!!!!)

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。

推薦閱讀: