2 * ============LICENSE_START=======================================================
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=========================================================
21 package org.onap.oom.certservice.certification;
23 import java.io.IOException;
24 import java.math.BigInteger;
25 import java.security.SecureRandom;
26 import java.time.LocalDateTime;
27 import java.time.ZoneOffset;
28 import java.util.Date;
29 import org.bouncycastle.asn1.ASN1Sequence;
30 import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
31 import org.bouncycastle.cert.X509v3CertificateBuilder;
32 import org.bouncycastle.pkcs.PKCS10CertificationRequest;
33 import org.springframework.stereotype.Component;
36 public class X509CertificateBuilder {
38 private static final int SECURE_NEXT_BYTES = 16;
39 private static final int VALID_PERIOD_IN_DAYS = 365;
41 X509v3CertificateBuilder build(PKCS10CertificationRequest csr) throws IOException {
42 return new X509v3CertificateBuilder(csr.getSubject(), createSerial(),
43 Date.from(LocalDateTime.now().toInstant(ZoneOffset.UTC)),
44 Date.from(LocalDateTime.now().plusDays(VALID_PERIOD_IN_DAYS).toInstant(ZoneOffset.UTC)),
45 new PKCS10CertificationRequest(csr.getEncoded()).getSubject(),
46 SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(csr.getSubjectPublicKeyInfo().getEncoded())));
50 private BigInteger createSerial() {
51 byte[] serial = new byte[SECURE_NEXT_BYTES];
52 new SecureRandom().nextBytes(serial);
53 return new BigInteger(serial).abs();