use of org.bouncycastle.asn1.x509.Attribute in project keystore-explorer by kaikramer.
the class X509Ext method getSubjectDirectoryAttributesStringValue.
private String getSubjectDirectoryAttributesStringValue(byte[] value) throws IOException {
// @formatter:off
/*
* SubjectDirectoryAttributes ::= ASN1Sequence SIZE (1..MAX) OF Attribute
*
* Attribute ::= ASN1Sequence
* {
* type AttributeType,
* values SET OF AttributeValue
* }
*/
// @formatter:on
StringBuilder sb = new StringBuilder();
SubjectDirectoryAttributes subjectDirectoryAttributes = SubjectDirectoryAttributes.getInstance(value);
for (Object attribute : subjectDirectoryAttributes.getAttributes()) {
ASN1ObjectIdentifier attributeType = ((Attribute) attribute).getAttrType();
String attributeTypeStr = attributeType.getId();
ASN1Encodable[] attributeValues = ((Attribute) attribute).getAttributeValues();
for (ASN1Encodable attributeValue : attributeValues) {
String attributeValueStr = getAttributeValueString(attributeType, attributeValue);
sb.append(MessageFormat.format("{0}={1}", attributeTypeStr, attributeValueStr));
sb.append(NEWLINE);
}
}
return sb.toString();
}
use of org.bouncycastle.asn1.x509.Attribute in project keystore-explorer by kaikramer.
the class Pkcs8Util method getEncryptionType.
/**
* Detect if a PKCS #8 private key is encrypted or not.
*
* @param is
* Input stream containing PKCS #8 private key
* @return Encryption type or null if not a valid PKCS #8 private key
* @throws IOException
* If an I/O problem occurred
*/
public static EncryptionType getEncryptionType(InputStream is) throws IOException {
byte[] pkcs8 = ReadUtil.readFully(is);
PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(pkcs8));
// PEM encoded?
if (pemInfo != null) {
String pemType = pemInfo.getType();
// Encrypted in pem format?
if (pemType.equals(Pkcs8Util.PKCS8_ENC_PVK_PEM_TYPE)) {
return ENCRYPTED;
} else // Unencrypted in pem format?
if (pemType.equals(Pkcs8Util.PKCS8_UNENC_PVK_PEM_TYPE)) {
return UNENCRYPTED;
}
}
// In ASN.1 format?
try {
// Read in an ASN.1 and check structure against the following
ASN1Primitive key = ASN1Primitive.fromByteArray(pkcs8);
if (key instanceof ASN1Sequence) {
ASN1Sequence sequence = (ASN1Sequence) key;
// May be unencrypted
if ((sequence.size() == 3) || (sequence.size() == 4)) {
// @formatter:off
/*
* Unencrypted PKCS #8 Private Key:
*
* PrivateKeyInfo ::= ASN1Sequence { version Version,
* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
* privateKey PrivateKey, attributes [0] IMPLICIT Attributes
* OPTIONAL }
*
* Version ::= ASN1Integer PrivateKeyAlgorithmIdentifier ::=
* AlgorithmIdentifier PrivateKey ::= OCTET STRING
* Attributes ::= SET OF Attribute
*/
// @formatter:on
Object obj1 = sequence.getObjectAt(0);
Object obj2 = sequence.getObjectAt(1);
Object obj3 = sequence.getObjectAt(2);
if (!(obj1 instanceof ASN1Integer)) {
return null;
}
ASN1Integer version = (ASN1Integer) obj1;
if (!version.getValue().equals(BigInteger.ZERO)) {
return null;
}
if (!(obj2 instanceof ASN1Sequence)) {
return null;
}
if (!sequenceIsAlgorithmIdentifier((ASN1Sequence) obj2)) {
return null;
}
if (!(obj3 instanceof ASN1OctetString)) {
return null;
}
return UNENCRYPTED;
} else // May be encrypted
if (sequence.size() == 2) {
// @formatter:off
/*
* Encrypted PKCS #8 Private Key:
*
* EncryptedPrivateKeyInfo ::= ASN1Sequence {
* encryptionAlgorithm EncryptionAlgorithmIdentifier,
* encryptedData EncryptedData }
*
* EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
* EncryptedData ::= OCTET STRING
*/
// @formatter:on
Object obj1 = sequence.getObjectAt(0);
Object obj2 = sequence.getObjectAt(1);
if (!(obj1 instanceof ASN1Sequence)) {
return null;
}
if (!sequenceIsAlgorithmIdentifier((ASN1Sequence) obj1)) {
return null;
}
if (!(obj2 instanceof ASN1OctetString)) {
return null;
}
return ENCRYPTED;
}
}
} catch (Exception ex) {
// Structure not as expected for PKCS #8
return null;
}
return null;
}
use of org.bouncycastle.asn1.x509.Attribute in project keystore-explorer by kaikramer.
the class Pkcs10Util method generateCsr.
/**
* Create a PKCS #10 certificate signing request (CSR) using the supplied
* certificate, private key and signature algorithm.
*
* @param cert
* The certificate
* @param privateKey
* The private key
* @param signatureType
* Signature
* @param challenge
* Challenge, optional, pass null if not required
* @param unstructuredName
* An optional company name, pass null if not required
* @param useExtensions
* Use extensions from cert for extensionRequest attribute?
* @throws CryptoException
* If there was a problem generating the CSR
* @return The CSR
*/
public static PKCS10CertificationRequest generateCsr(X509Certificate cert, PrivateKey privateKey, SignatureType signatureType, String challenge, String unstructuredName, boolean useExtensions, Provider provider) throws CryptoException {
try {
JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(cert.getSubjectX500Principal(), cert.getPublicKey());
// add challenge attribute
if (challenge != null) {
// PKCS#9 2.0: SHOULD use UTF8String encoding
csrBuilder.addAttribute(pkcs_9_at_challengePassword, new DERUTF8String(challenge));
}
if (unstructuredName != null) {
csrBuilder.addAttribute(pkcs_9_at_unstructuredName, new DERUTF8String(unstructuredName));
}
if (useExtensions) {
// add extensionRequest attribute with all extensions from the certificate
Certificate certificate = Certificate.getInstance(cert.getEncoded());
Extensions extensions = certificate.getTBSCertificate().getExtensions();
if (extensions != null) {
csrBuilder.addAttribute(pkcs_9_at_extensionRequest, extensions.toASN1Primitive());
}
}
// fall back to bouncy castle provider if given provider does not support the requested algorithm
if (provider != null && provider.getService("Signature", signatureType.jce()) == null) {
provider = new BouncyCastleProvider();
}
ContentSigner contentSigner = null;
if (provider == null) {
contentSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey);
} else {
contentSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider).build(privateKey);
}
PKCS10CertificationRequest csr = csrBuilder.build(contentSigner);
if (!verifyCsr(csr)) {
throw new CryptoException(res.getString("NoVerifyGenPkcs10Csr.exception.message"));
}
return csr;
} catch (CertificateEncodingException e) {
throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
} catch (OperatorCreationException e) {
throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
}
}
use of org.bouncycastle.asn1.x509.Attribute in project xipki by xipki.
the class X509SelfSignedCertBuilder method generateCertificate.
// method generateSelfSigned
private static X509Certificate generateCertificate(ConcurrentContentSigner signer, IdentifiedX509Certprofile certprofile, CertificationRequest csr, BigInteger serialNumber, SubjectPublicKeyInfo publicKeyInfo, List<String> caCertUris, List<String> ocspUris, List<String> crlUris, List<String> deltaCrlUris, ConfPairs extraControl) throws OperationException {
SubjectPublicKeyInfo tmpPublicKeyInfo;
try {
tmpPublicKeyInfo = X509Util.toRfc3279Style(publicKeyInfo);
} catch (InvalidKeySpecException ex) {
LOG.warn("SecurityUtil.toRfc3279Style", ex);
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
}
try {
certprofile.checkPublicKey(tmpPublicKeyInfo);
} catch (BadCertTemplateException ex) {
LOG.warn("certprofile.checkPublicKey", ex);
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
}
X500Name requestedSubject = csr.getCertificationRequestInfo().getSubject();
SubjectInfo subjectInfo;
// subject
try {
subjectInfo = certprofile.getSubject(requestedSubject);
} catch (CertprofileException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, "exception in cert profile " + certprofile.getIdent());
} catch (BadCertTemplateException ex) {
LOG.warn("certprofile.getSubject", ex);
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
}
Date notBefore = certprofile.getNotBefore(null);
if (notBefore == null) {
notBefore = new Date();
}
CertValidity validity = certprofile.getValidity();
if (validity == null) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "no validity specified in the profile " + certprofile.getIdent());
}
Date notAfter = validity.add(notBefore);
X500Name grantedSubject = subjectInfo.getGrantedSubject();
X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(grantedSubject, serialNumber, notBefore, notAfter, grantedSubject, tmpPublicKeyInfo);
PublicCaInfo publicCaInfo = new PublicCaInfo(grantedSubject, serialNumber, null, null, caCertUris, ocspUris, crlUris, deltaCrlUris, extraControl);
Extensions extensions = null;
ASN1Set attrs = csr.getCertificationRequestInfo().getAttributes();
for (int i = 0; i < attrs.size(); i++) {
Attribute attr = Attribute.getInstance(attrs.getObjectAt(i));
if (PKCSObjectIdentifiers.pkcs_9_at_extensionRequest.equals(attr.getAttrType())) {
extensions = Extensions.getInstance(attr.getAttributeValues()[0]);
}
}
try {
addExtensions(certBuilder, certprofile, requestedSubject, grantedSubject, extensions, tmpPublicKeyInfo, publicCaInfo, notBefore, notAfter);
ConcurrentBagEntrySigner signer0 = signer.borrowSigner();
X509CertificateHolder certHolder;
try {
certHolder = certBuilder.build(signer0.value());
} finally {
signer.requiteSigner(signer0);
}
Certificate bcCert = certHolder.toASN1Structure();
return X509Util.parseCert(bcCert.getEncoded());
} catch (BadCertTemplateException ex) {
throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
} catch (NoIdleSignerException | CertificateException | IOException | CertprofileException ex) {
throw new OperationException(ErrorCode.SYSTEM_FAILURE, ex);
}
}
use of org.bouncycastle.asn1.x509.Attribute in project xipki by xipki.
the class X509CaCmpResponderImpl method processP10cr.
// method processCertReqMessages
/**
* handle the PKI body with the choice {@code p10cr}<br/>
* Since it is not possible to add attribute to the PKCS#10 request (CSR), the certificate
* profile must be specified in the attribute regInfo-utf8Pairs (1.3.6.1.5.5.7.5.2.1) within
* PKIHeader.generalInfo
*/
private PKIBody processP10cr(PKIMessage request, CmpRequestorInfo requestor, ASN1OctetString tid, PKIHeader reqHeader, CertificationRequest p10cr, CmpControl cmpControl, String msgId, AuditEvent event) {
// verify the POP first
CertResponse certResp;
ASN1Integer certReqId = new ASN1Integer(-1);
boolean certGenerated = false;
X509Ca ca = getCa();
if (!securityFactory.verifyPopo(p10cr, getCmpControl().getPopoAlgoValidator())) {
LOG.warn("could not validate POP for the pkcs#10 requst");
certResp = buildErrorCertResponse(certReqId, PKIFailureInfo.badPOP, "invalid POP");
} else {
CertificationRequestInfo certTemp = p10cr.getCertificationRequestInfo();
Extensions extensions = CaUtil.getExtensions(certTemp);
X500Name subject = certTemp.getSubject();
SubjectPublicKeyInfo publicKeyInfo = certTemp.getSubjectPublicKeyInfo();
CmpUtf8Pairs keyvalues = CmpUtil.extract(reqHeader.getGeneralInfo());
String certprofileName = null;
Date notBefore = null;
Date notAfter = null;
if (keyvalues != null) {
certprofileName = keyvalues.value(CmpUtf8Pairs.KEY_CERTPROFILE);
String str = keyvalues.value(CmpUtf8Pairs.KEY_NOTBEFORE);
if (str != null) {
notBefore = DateUtil.parseUtcTimeyyyyMMddhhmmss(str);
}
str = keyvalues.value(CmpUtf8Pairs.KEY_NOTAFTER);
if (str != null) {
notAfter = DateUtil.parseUtcTimeyyyyMMddhhmmss(str);
}
}
if (certprofileName == null) {
certResp = buildErrorCertResponse(certReqId, PKIFailureInfo.badCertTemplate, "badCertTemplate", null);
} else {
certprofileName = certprofileName.toLowerCase();
if (!requestor.isCertProfilePermitted(certprofileName)) {
String msg = "certprofile " + certprofileName + " is not allowed";
certResp = buildErrorCertResponse(certReqId, PKIFailureInfo.notAuthorized, msg);
} else {
CertTemplateData certTemplateData = new CertTemplateData(subject, publicKeyInfo, notBefore, notAfter, extensions, certprofileName);
certResp = generateCertificates(Arrays.asList(certTemplateData), Arrays.asList(certReqId), requestor, tid, false, request, cmpControl, msgId, event).get(0);
certGenerated = true;
}
}
}
CMPCertificate[] caPubs = null;
if (certGenerated && cmpControl.isSendCaCert()) {
caPubs = new CMPCertificate[] { ca.getCaInfo().getCertInCmpFormat() };
}
CertRepMessage repMessage = new CertRepMessage(caPubs, new CertResponse[] { certResp });
return new PKIBody(PKIBody.TYPE_CERT_REP, repMessage);
}
Aggregations