1. 程式人生 > 其它 >Golang-RSA2 簽名及驗籤

Golang-RSA2 簽名及驗籤

技術標籤:gogo

const (
    // 私鑰 PEMBEGIN 開頭
    PEMBEGIN = "-----BEGIN RSA PRIVATE KEY-----\n"
    // 私鑰 PEMEND 結尾
    PEMEND = "\n-----END RSA PRIVATE KEY-----"
    // 公鑰 PEMBEGIN 開頭
    PUBPEMBEGIN = "-----BEGIN PUBLIC KEY-----\n"
    // 公鑰 PEMEND 結尾
    PUBPEMEND = "\n-----END PUBLIC KEY-----"
)
// Rsa2Sign RSA2私鑰簽名
func Rsa2Sign(signContent string, privateKey string, hash crypto.Hash) string {
    shaNew := hash.New()
    shaNew.Write([]byte(signContent))
    hashed := shaNew.Sum(nil)
    priKey, err := ParsePrivateKey(privateKey)
    if err != nil {
        return ""
    }

    signature, err := rsa.SignPKCS1v15(rand.Reader, priKey, hash, hashed)
    if err != nil {
        return ""
    }
    return base64.StdEncoding.EncodeToString(signature)
}

// ParsePrivateKey 私鑰驗證
func ParsePrivateKey(privateKey string) (*rsa.PrivateKey, error) {
    privateKey = FormatPrivateKey(privateKey)
    block, _ := pem.Decode([]byte(privateKey))
    if block == nil {
        return nil, errors.New("私鑰資訊錯誤!")
    }
    priKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    if err != nil {
        return nil, err
    }
    return priKey, nil
}

// FormatPrivateKey 組裝私鑰
func FormatPrivateKey(privateKey string) string {
    if !strings.HasPrefix(privateKey, PEMBEGIN) {
        privateKey = PEMBEGIN + privateKey
    }
    if !strings.HasSuffix(privateKey, PEMEND) {
        privateKey = privateKey + PEMEND
    }
    return privateKey
}

// Rsa2PubSign RSA2公鑰驗證簽名
func Rsa2PubSign(signContent, sign, publicKey string, hash crypto.Hash) bool {
    hashed := sha256.Sum256([]byte(signContent))
    pubKey, err := ParsePublicKey(publicKey)
    if err != nil {
        log.Errorf(err, "rsa2 public check sign failed.")
        return false
    }
    sig, _ := base64.StdEncoding.DecodeString(sign)
    err = rsa.VerifyPKCS1v15(pubKey, hash, hashed[:], sig)
    if err != nil {
        log.Errorf(err, "rsa2 public check sign failed.")
        return false
    }
    return true
}

// ParsePublicKey 公鑰驗證
func ParsePublicKey(publicKey string) (*rsa.PublicKey, error) {
    publicKey = FormatPublicKey(publicKey)
    block, _ := pem.Decode([]byte(publicKey))
    if block == nil {
        return nil, errors.New("公鑰資訊錯誤!")
    }
    pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
    if err != nil {
        return nil, err
    }
    return pubKey.(*rsa.PublicKey), nil
}

// FormatPublicKey 組裝公鑰
func FormatPublicKey(publicKey string) string {
    if !strings.HasPrefix(publicKey, PUBPEMBEGIN) {
        publicKey = PUBPEMBEGIN + publicKey
    }
    if !strings.HasSuffix(publicKey, PUBPEMEND) {
        publicKey = publicKey + PUBPEMEND
    }
    return publicKey
}