Debian Codegraph @

encode.go

raw symbols SCIP
1 // Modified by 42wim
2 //
3 // Copyright 2021 The Sigstore Authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16
17 package sshsig
18
19 import (
20 "errors"
21 "fmt"
22
23 "github.com/42wim/sshsig/pem"
24
25 "golang.org/x/crypto/ssh"
26 )
27
28 const (
29 pemType = "SSH SIGNATURE"
30 )
31
32 // Armored returns the signature in an armored format.
33 func Armor(s *ssh.Signature, p ssh.PublicKey, ns string) []byte {
34 sig := WrappedSig{
35 Version: 1,
36 PublicKey: string(p.Marshal()),
37 Namespace: ns,
38 HashAlgorithm: defaultHashAlgorithm,
39 Signature: string(ssh.Marshal(s)),
40 }
41
42 copy(sig.MagicHeader[:], magicHeader)
43
44 enc := pem.EncodeToMemory(&pem.Block{
45 Type: pemType,
46 Bytes: ssh.Marshal(sig),
47 })
48 return enc
49 }
50
51 // Decode parses an armored signature.
52 func Decode(b []byte) (*Signature, error) {
53 pemBlock, _ := pem.Decode(b)
54 if pemBlock == nil {
55 return nil, errors.New("unable to decode pem file")
56 }
57
58 if pemBlock.Type != pemType {
59 return nil, fmt.Errorf("wrong pem block type: %s. Expected SSH-SIGNATURE", pemBlock.Type)
60 }
61
62 // Now we unmarshal it into the Signature block
63 sig := WrappedSig{}
64 if err := ssh.Unmarshal(pemBlock.Bytes, &sig); err != nil {
65 return nil, err
66 }
67
68 if sig.Version != 1 {
69 return nil, fmt.Errorf("unsupported signature version: %d", sig.Version)
70 }
71 if string(sig.MagicHeader[:]) != magicHeader {
72 return nil, fmt.Errorf("invalid magic header: %s", sig.MagicHeader[:])
73 }
74 if _, ok := supportedHashAlgorithms[sig.HashAlgorithm]; !ok {
75 return nil, fmt.Errorf("unsupported hash algorithm: %s", sig.HashAlgorithm)
76 }
77
78 // Now we can unpack the Signature and PublicKey blocks
79 sshSig := ssh.Signature{}
80 if err := ssh.Unmarshal([]byte(sig.Signature), &sshSig); err != nil {
81 return nil, err
82 }
83 // TODO: check the format here (should be rsa-sha512)
84
85 pk, err := ssh.ParsePublicKey([]byte(sig.PublicKey))
86 if err != nil {
87 return nil, err
88 }
89
90 return &Signature{
91 signature: &sshSig,
92 pk: pk,
93 hashAlg: sig.HashAlgorithm,
94 }, nil
95 }