aboutsummaryrefslogtreecommitdiff
path: root/rsa.go
blob: 166116335c97de85ddd8274bc8ac704d387f8313 (plain) (blame)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package pki

import (
  "crypto"
  "crypto/rand"
  "crypto/rsa"
  "crypto/x509"
  "encoding/pem"
  "errors"
)

const (
  PemLabelRsa = "RSA PRIVATE KEY"
)

type (
  RsaPrivateKey struct {
    private_key *rsa.PrivateKey
  }

  RsaPublicKey struct {
    public_key *rsa.PublicKey
  }
)

// generate a new rsa private key
func NewPrivateKeyRsa(size int) (*RsaPrivateKey, error) {
  key, err := rsa.GenerateKey(rand.Reader, size)
  if err != nil { return nil, err }
  return &RsaPrivateKey{key}, nil
}

// load a rsa private key its ASN.1 presentation
func LoadPrivateKeyRsa(raw []byte) (*RsaPrivateKey, error) {
  key, err := x509.ParsePKCS1PrivateKey(raw)
  if err != nil { return nil, err }
  return &RsaPrivateKey{key}, nil
}

func (pr *RsaPrivateKey) Public() PublicKey {
  return &RsaPublicKey{pr.private_key.Public().(*rsa.PublicKey)}
}

func (pr RsaPrivateKey) Sign(message []byte, hash crypto.Hash) ([]byte, error) {
  return make([]byte, 0), errors.New("not implemented yet!")
}

// get the private key
func (pr RsaPrivateKey) privateKey() crypto.PrivateKey {
  return pr.private_key
}

func (pr RsaPrivateKey) MarshalPem() (marshalledPemBlock, error) {
  asn1 := x509.MarshalPKCS1PrivateKey(pr.private_key)
  pem_block := pem.Block{Type: PemLabelRsa, Bytes: asn1}
  return pem.EncodeToMemory(&pem_block), nil
}

func LoadPublicKeyRsa(raw []byte) (*RsaPublicKey, error) {
  return nil, errors.New("not implemented yet!")
}

func (pu *RsaPublicKey) MarshalPem() (marshalledPemBlock, error) {
  asn1, err := x509.MarshalPKIXPublicKey(pu.public_key)
  if err != nil { return nil, err }
  pem_block := pem.Block{Type: PemLabelPublic, Bytes: asn1}
  return pem.EncodeToMemory(&pem_block), nil
}

func (pu *RsaPublicKey) Verify(message []byte, signature []byte, hash crypto.Hash) (bool, error) {
  return false, errors.New("not implemented yet!")
}