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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
31 PemCsrType = "CERTIFICATE REQUEST"
32 pemPrivateKeyType = "PRIVATE KEY"
35 // decodeCSR decodes a certificate request in PEM format
36 func DecodeCSR(data []byte) (*x509.CertificateRequest, error) {
37 block, err := decodePemBlock(data, PemCsrType)
39 return nil, fmt.Errorf("error decoding CSR PEM: %v", err)
41 csr, err := x509.ParseCertificateRequest(block.Bytes)
43 return nil, fmt.Errorf("error parsing certificate request: %v", err)
45 if err := csr.CheckSignature(); err != nil {
46 return nil, fmt.Errorf("error checking certificate request signature: %v", err)
51 func DecodePrivateKey(data []byte) (interface{}, error) {
52 block, err := decodePemBlock(data, pemPrivateKeyType)
54 return nil, fmt.Errorf("error decoding Private Key PEM: %v", err)
56 key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
58 return nil, fmt.Errorf("error parsing Private Key: %v", err)
63 func decodePemBlock(data []byte, pemType string) (*pem.Block, error) {
64 block, rest := pem.Decode(data)
65 if block == nil || len(rest) > 0 {
66 return nil, fmt.Errorf("unexpected PEM")
68 if block.Type != pemType {
69 return nil, fmt.Errorf("PEM is not: %s", pemType)
75 func ParseCertificateArrayToBytes(certificateArray []string) ([]byte, error) {
76 buffer := bytes.NewBuffer([]byte{})
77 for _, cert := range certificateArray {
78 block, _ := pem.Decode([]byte(cert))
79 err := pem.Encode(buffer, &pem.Block{Type: "CERTIFICATE", Bytes: block.Bytes})
84 return buffer.Bytes(), nil