Debian Codegraph @

jose-util/crypto.go

raw
1 /*-
2 * Copyright 2019 Square Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package main
18
19 import (
20 "github.com/go-jose/go-jose/jose-util/generator"
21 jose "github.com/go-jose/go-jose/v3"
22 )
23
24 func encrypt() {
25 pub, err := generator.LoadPublicKey(keyBytes())
26 app.FatalIfError(err, "unable to read public key")
27
28 alg := jose.KeyAlgorithm(*encryptAlgFlag)
29 enc := jose.ContentEncryption(*encryptEncFlag)
30
31 crypter, err := jose.NewEncrypter(enc, jose.Recipient{Algorithm: alg, Key: pub}, nil)
32 app.FatalIfError(err, "unable to instantiate encrypter")
33
34 obj, err := crypter.Encrypt(readInput(*inFile))
35 app.FatalIfError(err, "unable to encrypt")
36
37 var msg string
38 if *encryptFullFlag {
39 msg = obj.FullSerialize()
40 } else {
41 msg, err = obj.CompactSerialize()
42 app.FatalIfError(err, "unable to serialize message")
43 }
44
45 writeOutput(*outFile, []byte(msg))
46 }
47
48 func decrypt() {
49 priv, err := generator.LoadPrivateKey(keyBytes())
50 app.FatalIfError(err, "unable to read private key")
51
52 obj, err := jose.ParseEncrypted(string(readInput(*inFile)))
53 app.FatalIfError(err, "unable to parse message")
54
55 plaintext, err := obj.Decrypt(priv)
56 app.FatalIfError(err, "unable to decrypt message")
57
58 writeOutput(*outFile, plaintext)
59 }
60
61 func sign() {
62 signingKey, err := generator.LoadPrivateKey(keyBytes())
63 app.FatalIfError(err, "unable to read private key")
64
65 alg := jose.SignatureAlgorithm(*signAlgFlag)
66 signer, err := jose.NewSigner(jose.SigningKey{Algorithm: alg, Key: signingKey}, nil)
67 app.FatalIfError(err, "unable to make signer")
68
69 obj, err := signer.Sign(readInput(*inFile))
70 app.FatalIfError(err, "unable to sign")
71
72 var msg string
73 if *signFullFlag {
74 msg = obj.FullSerialize()
75 } else {
76 msg, err = obj.CompactSerialize()
77 app.FatalIfError(err, "unable to serialize message")
78 }
79
80 writeOutput(*outFile, []byte(msg))
81 }
82
83 func verify() {
84 verificationKey, err := generator.LoadPublicKey(keyBytes())
85 app.FatalIfError(err, "unable to read public key")
86
87 obj, err := jose.ParseSigned(string(readInput(*inFile)))
88 app.FatalIfError(err, "unable to parse message")
89
90 plaintext, err := obj.Verify(verificationKey)
91 app.FatalIfError(err, "invalid signature")
92
93 writeOutput(*outFile, plaintext)
94 }