forked from denro/nordnet
/
util.go
57 lines (46 loc) · 1.22 KB
/
util.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
// Package util contains utility functions
package util
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"strconv"
"time"
)
const Stockholm_Timezone = "Europe/Stockholm"
func GenerateCredentials(username, password, rawPem []byte) (cred string, err error) {
var loc *time.Location
if loc, err = time.LoadLocation(Stockholm_Timezone); err != nil {
return
}
ms := time.Now().In(loc).Unix() * 1000
unixStr := strconv.FormatInt(ms, 10)
userBase64 := base64.StdEncoding.EncodeToString(username)
passBase64 := base64.StdEncoding.EncodeToString(password)
timeBase64 := base64.StdEncoding.EncodeToString([]byte(unixStr))
formated := fmt.Sprintf("%s:%s:%s", userBase64, passBase64, timeBase64)
block, _ := pem.Decode(rawPem)
if block == nil {
err = errors.New("Could not Decode PEM")
return
}
pubKeyVal, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return
}
rsaPubKey, ok := pubKeyVal.(*rsa.PublicKey)
if !ok {
err = errors.New("Could not make DER to an RSA PublicKey")
return
}
encr, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPubKey, []byte(formated))
if err != nil {
return
}
cred = base64.StdEncoding.EncodeToString(encr)
return
}