Debian Codegraph @

jose/encrypt.go

raw symbols SCIP
1 package jose
2
3 import (
4 "crypto"
5 "encoding/base64"
6 "encoding/json"
7
8 "github.com/pkg/errors"
9 "github.com/smallstep/cli/crypto/randutil"
10 "github.com/smallstep/cli/errs"
11 "github.com/smallstep/cli/ui"
12 )
13
14 // Thumbprint computes the JWK Thumbprint of a key using SHA256 as the hash
15 // algorithm. It returns the hash encoded in the Base64 raw url encoding.
16 func Thumbprint(jwk *JSONWebKey) (string, error) {
17 hash, err := jwk.Thumbprint(crypto.SHA256)
18 if err != nil {
19 return "", errors.Wrap(err, "error generating JWK thumbprint")
20 }
21 return base64.RawURLEncoding.EncodeToString(hash), nil
22 }
23
24 // EncryptJWK returns the given JWK encrypted with the default encryption
25 // algorithm (PBES2-HS256+A128KW).
26 func EncryptJWK(jwk *JSONWebKey, opts ...Option) (*JSONWebEncryption, error) {
27 ctx, err := new(context).apply(opts...)
28 if err != nil {
29 return nil, err
30 }
31
32 var key []byte
33 if len(ctx.password) > 0 {
34 key = ctx.password
35 } else {
36 key, err = ui.PromptPassword("Please enter the password to encrypt the private JWK")
37 if err != nil {
38 return nil, errors.Wrap(err, "error reading password")
39 }
40 }
41
42 salt, err := randutil.Salt(PBKDF2SaltSize)
43 if err != nil {
44 return nil, err
45 }
46
47 b, err := json.Marshal(jwk)
48 if err != nil {
49 return nil, errors.Wrap(err, "error marshaling JWK")
50 }
51
52 // Encrypt private key using PBES2
53 recipient := Recipient{
54 Algorithm: PBES2_HS256_A128KW,
55 Key: key,
56 PBES2Count: PBKDF2Iterations,
57 PBES2Salt: salt,
58 }
59
60 encOpts := new(EncrypterOptions)
61 encOpts.WithContentType(ContentType("jwk+json"))
62
63 encrypter, err := NewEncrypter(DefaultEncAlgorithm, recipient, encOpts)
64 if err != nil {
65 return nil, errs.Wrap(err, "error creating cipher")
66 }
67
68 jwe, err := encrypter.Encrypt(b)
69 if err != nil {
70 return nil, errs.Wrap(err, "error encrypting data")
71 }
72
73 return jwe, nil
74 }