2024-02-01 16:41:39 +05:30
|
|
|
package security
|
2021-02-26 07:15:45 +05:30
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto"
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/rsa"
|
|
|
|
"crypto/sha1"
|
2024-03-05 17:37:54 +05:30
|
|
|
"crypto/x509"
|
|
|
|
"encoding/pem"
|
|
|
|
"errors"
|
|
|
|
"io"
|
2021-02-26 07:15:45 +05:30
|
|
|
)
|
|
|
|
|
|
|
|
var randomReader = rand.Reader
|
2024-03-05 17:37:54 +05:30
|
|
|
var invalidKeyFormat = errors.New(`invalid key format: it should be"der" or "pem"`)
|
2021-02-26 07:15:45 +05:30
|
|
|
|
2024-02-01 16:41:39 +05:30
|
|
|
func NewSigner(key *rsa.PrivateKey) *Signer {
|
|
|
|
return &Signer{Key: key}
|
|
|
|
}
|
|
|
|
|
2021-02-26 07:15:45 +05:30
|
|
|
type Signer struct {
|
|
|
|
Key *rsa.PrivateKey
|
|
|
|
}
|
|
|
|
|
2024-03-05 17:37:54 +05:30
|
|
|
func (s *Signer) Sign(data io.Reader) ([]byte, error) {
|
2021-02-26 07:15:45 +05:30
|
|
|
messageHash := sha1.New()
|
2024-03-05 17:37:54 +05:30
|
|
|
_, err := io.Copy(messageHash, data)
|
2024-02-01 16:41:39 +05:30
|
|
|
if err != nil {
|
2024-03-05 17:37:54 +05:30
|
|
|
return nil, err
|
2024-02-01 16:41:39 +05:30
|
|
|
}
|
2021-02-26 07:15:45 +05:30
|
|
|
|
2024-02-01 16:41:39 +05:30
|
|
|
messageHashSum := messageHash.Sum(nil)
|
2021-02-26 07:15:45 +05:30
|
|
|
signature, err := rsa.SignPKCS1v15(randomReader, s.Key, crypto.SHA1, messageHashSum)
|
|
|
|
if err != nil {
|
2024-03-05 17:37:54 +05:30
|
|
|
return nil, err
|
2021-02-26 07:15:45 +05:30
|
|
|
}
|
|
|
|
|
2024-03-05 17:37:54 +05:30
|
|
|
return signature, nil
|
2021-02-26 07:15:45 +05:30
|
|
|
}
|
|
|
|
|
2024-03-05 17:37:54 +05:30
|
|
|
func (s *Signer) GetPublicKey(format string) ([]byte, error) {
|
|
|
|
if format != "der" && format != "pem" {
|
|
|
|
return nil, invalidKeyFormat
|
|
|
|
}
|
|
|
|
|
|
|
|
asn1Bytes, err := x509.MarshalPKIXPublicKey(s.Key.Public())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if format == "pem" {
|
|
|
|
return pem.EncodeToMemory(&pem.Block{
|
|
|
|
Type: "PUBLIC KEY",
|
|
|
|
Bytes: asn1Bytes,
|
|
|
|
}), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return asn1Bytes, nil
|
2021-02-26 07:15:45 +05:30
|
|
|
}
|