Debian Codegraph @

utils.go

raw symbols SCIP
1 /*-
2 * Copyright 2014 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 jose
18
19 import (
20 "crypto/x509"
21 "encoding/pem"
22 "fmt"
23 )
24
25 // LoadPublicKey loads a public key from PEM/DER-encoded data.
26 func LoadPublicKey(data []byte) (interface{}, error) {
27 input := data
28
29 block, _ := pem.Decode(data)
30 if block != nil {
31 input = block.Bytes
32 }
33
34 // Try to load SubjectPublicKeyInfo
35 pub, err0 := x509.ParsePKIXPublicKey(input)
36 if err0 == nil {
37 return pub, nil
38 }
39
40 cert, err1 := x509.ParseCertificate(input)
41 if err1 == nil {
42 return cert.PublicKey, nil
43 }
44
45 return nil, fmt.Errorf("square/go-jose: parse error, got '%s' and '%s'", err0, err1)
46 }
47
48 // LoadPrivateKey loads a private key from PEM/DER-encoded data.
49 func LoadPrivateKey(data []byte) (interface{}, error) {
50 input := data
51
52 block, _ := pem.Decode(data)
53 if block != nil {
54 input = block.Bytes
55 }
56
57 var priv interface{}
58 priv, err0 := x509.ParsePKCS1PrivateKey(input)
59 if err0 == nil {
60 return priv, nil
61 }
62
63 priv, err1 := x509.ParsePKCS8PrivateKey(input)
64 if err1 == nil {
65 return priv, nil
66 }
67
68 priv, err2 := x509.ParseECPrivateKey(input)
69 if err2 == nil {
70 return priv, nil
71 }
72
73 return nil, fmt.Errorf("square/go-jose: parse error, got '%s', '%s' and '%s'", err0, err1, err2)
74 }