mirror of
https://github.com/elyby/chrly.git
synced 2025-05-31 14:11:51 +05:30
Implemented API endpoint to sign arbitrary data
This commit is contained in:
@@ -1,15 +1,18 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"io"
|
||||
)
|
||||
|
||||
var randomReader = rand.Reader
|
||||
var invalidKeyFormat = errors.New(`invalid key format: it should be"der" or "pem"`)
|
||||
|
||||
func NewSigner(key *rsa.PrivateKey) *Signer {
|
||||
return &Signer{Key: key}
|
||||
@@ -19,23 +22,38 @@ type Signer struct {
|
||||
Key *rsa.PrivateKey
|
||||
}
|
||||
|
||||
func (s *Signer) SignTextures(ctx context.Context, textures string) (string, error) {
|
||||
message := []byte(textures)
|
||||
func (s *Signer) Sign(data io.Reader) ([]byte, error) {
|
||||
messageHash := sha1.New()
|
||||
_, err := messageHash.Write(message)
|
||||
_, err := io.Copy(messageHash, data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
messageHashSum := messageHash.Sum(nil)
|
||||
signature, err := rsa.SignPKCS1v15(randomReader, s.Key, crypto.SHA1, messageHashSum)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return base64.StdEncoding.EncodeToString(signature), nil
|
||||
return signature, nil
|
||||
}
|
||||
|
||||
func (s *Signer) GetPublicKey(ctx context.Context) (*rsa.PublicKey, error) {
|
||||
return &s.Key.PublicKey, nil
|
||||
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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user