|
| 1 | +// |
| 2 | +// DISCLAIMER |
| 3 | +// |
| 4 | +// Copyright 2023 ArangoDB GmbH, Cologne, Germany |
| 5 | +// |
| 6 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +// you may not use this file except in compliance with the License. |
| 8 | +// You may obtain a copy of the License at |
| 9 | +// |
| 10 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +// |
| 12 | +// Unless required by applicable law or agreed to in writing, software |
| 13 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +// See the License for the specific language governing permissions and |
| 16 | +// limitations under the License. |
| 17 | +// |
| 18 | +// Copyright holder is ArangoDB GmbH, Cologne, Germany |
| 19 | +// |
| 20 | + |
| 21 | +package cert |
| 22 | + |
| 23 | +import ( |
| 24 | + "crypto" |
| 25 | + "crypto/rand" |
| 26 | + "crypto/rsa" |
| 27 | + "crypto/sha256" |
| 28 | + "crypto/x509" |
| 29 | + "encoding/base64" |
| 30 | + "encoding/pem" |
| 31 | +) |
| 32 | + |
| 33 | +type Signer struct { |
| 34 | + privateKey *rsa.PrivateKey |
| 35 | +} |
| 36 | + |
| 37 | +// NewSigner creates a new Signer with a generated private key. |
| 38 | +func NewSigner() (*Signer, error) { |
| 39 | + privateKey, err := rsa.GenerateKey(rand.Reader, 2048) |
| 40 | + if err != nil { |
| 41 | + return nil, err |
| 42 | + } |
| 43 | + return &Signer{privateKey: privateKey}, nil |
| 44 | +} |
| 45 | + |
| 46 | +// Sign signs the content with the private key and returns: |
| 47 | +// base64 encoded signature, base64 encoded content and error. |
| 48 | +func (s *Signer) Sign(content string) (string, string, error) { |
| 49 | + hash := sha256.New() |
| 50 | + hash.Write([]byte(content)) |
| 51 | + signature, err := rsa.SignPKCS1v15(rand.Reader, s.privateKey, crypto.SHA256, hash.Sum(nil)) |
| 52 | + if err != nil { |
| 53 | + return "", "", err |
| 54 | + } |
| 55 | + return base64.StdEncoding.EncodeToString(signature), base64.StdEncoding.EncodeToString([]byte(content)), nil |
| 56 | +} |
| 57 | + |
| 58 | +// PublicKey returns the public key in PKIX format. |
| 59 | +func (s *Signer) PublicKey() (string, error) { |
| 60 | + publicKey := &s.privateKey.PublicKey |
| 61 | + publicKeyDer, err := x509.MarshalPKIXPublicKey(publicKey) |
| 62 | + if err != nil { |
| 63 | + return "", err |
| 64 | + } |
| 65 | + |
| 66 | + publicKeyBlock := pem.Block{ |
| 67 | + Type: "RSA PUBLIC KEY", |
| 68 | + Bytes: publicKeyDer, |
| 69 | + } |
| 70 | + return string(pem.EncodeToMemory(&publicKeyBlock)), nil |
| 71 | +} |
0 commit comments