56 lines
1.1 KiB
Go
56 lines
1.1 KiB
Go
|
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
|
||
|
|
||
|
package signature
|
||
|
|
||
|
import (
|
||
|
"crypto"
|
||
|
"crypto/rand"
|
||
|
"crypto/rsa"
|
||
|
"crypto/sha256"
|
||
|
"crypto/x509"
|
||
|
"encoding/pem"
|
||
|
"fmt"
|
||
|
"os"
|
||
|
)
|
||
|
|
||
|
var ErrInvalidSignature error = errors.New("Invalid signature")
|
||
|
|
||
|
type Ident struct {
|
||
|
authorized []string
|
||
|
publicKey *rsa.PublicKey
|
||
|
privateKey *rsa.PrivateKey
|
||
|
}
|
||
|
|
||
|
func NewIdent() *Ident {
|
||
|
i := &Ident{}
|
||
|
i.authorized = []string{ "*" }
|
||
|
i.Generate()
|
||
|
return i
|
||
|
}
|
||
|
|
||
|
func (i *Ident) Generate() error {
|
||
|
var err error
|
||
|
i.privateKey, err = rsa.GenerateKey(rand.Reader, 2048)
|
||
|
i.publicKey = &privateKey.PublicKey
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
func (i *Ident) Sign(data []byte) ([]byte, error) {
|
||
|
checksum := sha256.Sum256(data)
|
||
|
sig, e := rsa.SignPKCS1v15(rand.Reader, i.privateKey, crypto.SHA256, checksum[:])
|
||
|
if e != nil {
|
||
|
return e
|
||
|
}
|
||
|
return sig, e
|
||
|
}
|
||
|
|
||
|
func (i *Ident) Verify(data []byte, signature []byte) error {
|
||
|
checksum := sha256.Sum256(data)
|
||
|
return rsa.VerifyPKCS1v15(i.publicKey, crypto.SHA256, checksum[:], signature)
|
||
|
}
|
||
|
|
||
|
func (i *Ident) VerifySum(checksum []byte, signature []byte) error {
|
||
|
return rsa.VerifyPKCS1v15(i.publicKey, crypto.SHA256, checksum[:], signature)
|
||
|
}
|
||
|
|