-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenssl_private_encrypt.go
49 lines (40 loc) · 1.11 KB
/
openssl_private_encrypt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Copyright (c) 2018, [email protected]. All Rights Reserved.
//
package chenxi_package
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
)
// RSA PKCS8 private key format
// "
// -----BEGIN RSA PRIVATE KEY-----
// MIIE****
// -----END RSA PRIVATE KEY-----
// "
//
// var inputPrivateKey string
func signWithRsaPrivateKey(message, inputPrivateKey string) (string, error) {
block, _ := pem.Decode([]byte(inputPrivateKey))
if block == nil {
return "", fmt.Errorf("no key found")
}
if block.Type != "RSA PRIVATE KEY" {
return "", fmt.Errorf("unsupported key type %q", block.Type)
}
rsaPrivateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return "", err
}
// Sign secret with rsa with PKCS 1.5 as the padding algorithm
// The result is exactly same as "openssl rsautl -sign -inkey "inputPrivateKey_in_file" -in "YOUR_PLAIN_TEXT""
signer, err := rsa.SignPKCS1v15(rand.Reader, rsaPrivateKey.(*rsa.PrivateKey), crypto.Hash(0), []byte(message))
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(signer), nil
}