forked from dghubble/oauth1
-
Notifications
You must be signed in to change notification settings - Fork 2
/
signer.go
62 lines (54 loc) · 1.76 KB
/
signer.go
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
package oauth1
import (
"crypto"
"crypto/hmac"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"encoding/base64"
"strings"
)
// A Signer signs messages to create signed OAuth1 Requests.
type Signer interface {
// Name returns the name of the signing method.
Name() string
// Sign signs the message using the given secret key.
Sign(key string, message string) (string, error)
}
// HMACSigner signs messages with an HMAC SHA1 digest, using the concatenated
// consumer secret and token secret as the key.
type HMACSigner struct {
ConsumerSecret string
}
// Name returns the HMAC-SHA1 method.
func (s *HMACSigner) Name() string {
return "HMAC-SHA1"
}
// Sign creates a concatenated consumer and token secret key and calculates
// the HMAC digest of the message. Returns the base64 encoded digest bytes.
func (s *HMACSigner) Sign(tokenSecret, message string) (string, error) {
signingKey := strings.Join([]string{s.ConsumerSecret, tokenSecret}, "&")
mac := hmac.New(sha1.New, []byte(signingKey))
mac.Write([]byte(message))
signatureBytes := mac.Sum(nil)
return base64.StdEncoding.EncodeToString(signatureBytes), nil
}
// RSASigner RSA PKCS1-v1_5 signs SHA1 digests of messages using the given
// RSA private key.
type RSASigner struct {
PrivateKey *rsa.PrivateKey
}
// Name returns the RSA-SHA1 method.
func (s *RSASigner) Name() string {
return "RSA-SHA1"
}
// Sign uses RSA PKCS1-v1_5 to sign a SHA1 digest of the given message. The
// tokenSecret is not used with this signing scheme.
func (s *RSASigner) Sign(tokenSecret, message string) (string, error) {
digest := sha1.Sum([]byte(message))
signature, err := rsa.SignPKCS1v15(rand.Reader, s.PrivateKey, crypto.SHA1, digest[:])
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(signature), nil
}