[OOM-K8S-CERT-EXTERNAL-PROVIDER] Add logging of supported CSR properties
[oom/platform/cert-service.git] / certServiceK8sExternalProvider / src / x509 / x509_utils.go
1 /*
2  * ============LICENSE_START=======================================================
3  * oom-certservice-k8s-external-provider
4  * ================================================================================
5  * Copyright (C) 2020 Nokia. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package x509
22
23 import (
24         "bytes"
25         "crypto/x509"
26         "encoding/pem"
27         "fmt"
28 )
29
30 // decodeCSR decodes a certificate request in PEM format and returns the
31 func DecodeCSR(data []byte) (*x509.CertificateRequest, error) {
32         block, rest := pem.Decode(data)
33         if block == nil || len(rest) > 0 {
34                 return nil, fmt.Errorf("unexpected CSR PEM on sign request")
35         }
36         if block.Type != "CERTIFICATE REQUEST" {
37                 return nil, fmt.Errorf("PEM is not a certificate request")
38         }
39         csr, err := x509.ParseCertificateRequest(block.Bytes)
40         if err != nil {
41                 return nil, fmt.Errorf("error parsing certificate request: %v", err)
42         }
43         if err := csr.CheckSignature(); err != nil {
44                 return nil, fmt.Errorf("error checking certificate request signature: %v", err)
45         }
46         return csr, nil
47 }
48
49 // encodeX509 will encode a *x509.Certificate into PEM format.
50 func EncodeX509(cert *x509.Certificate) ([]byte, error) {
51         caPem := bytes.NewBuffer([]byte{})
52         err := pem.Encode(caPem, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
53         if err != nil {
54                 return nil, err
55         }
56         return caPem.Bytes(), nil
57 }