use of com.github.zhenwei.core.asn1.DEROctetString in project xipki by xipki.
the class CmpResponder method processPkiMessage.
public PKIMessage processPkiMessage(PKIMessage pkiMessage, X509Certificate tlsClientCert, AuditEvent event) {
ParamUtil.requireNonNull("pkiMessage", pkiMessage);
ParamUtil.requireNonNull("event", event);
GeneralPKIMessage message = new GeneralPKIMessage(pkiMessage);
PKIHeader reqHeader = message.getHeader();
ASN1OctetString tid = reqHeader.getTransactionID();
String msgId = null;
if (event != null) {
msgId = RandomUtil.nextHexLong();
event.addEventData(CaAuditConstants.NAME_mid, msgId);
}
if (tid == null) {
byte[] randomBytes = randomTransactionId();
tid = new DEROctetString(randomBytes);
}
String tidStr = Base64.encodeToString(tid.getOctets());
if (event != null) {
event.addEventData(CaAuditConstants.NAME_tid, tidStr);
}
int reqPvno = reqHeader.getPvno().getValue().intValue();
if (reqPvno != PVNO_CMP2000) {
if (event != null) {
event.setLevel(AuditLevel.INFO);
event.setStatus(AuditStatus.FAILED);
event.addEventData(CaAuditConstants.NAME_message, "unsupproted version " + reqPvno);
}
return buildErrorPkiMessage(tid, reqHeader, PKIFailureInfo.unsupportedVersion, null);
}
CmpControl cmpControl = getCmpControl();
Integer failureCode = null;
String statusText = null;
Date messageTime = null;
if (reqHeader.getMessageTime() != null) {
try {
messageTime = reqHeader.getMessageTime().getDate();
} catch (ParseException ex) {
LogUtil.error(LOG, ex, "tid=" + tidStr + ": could not parse messageTime");
}
}
GeneralName recipient = reqHeader.getRecipient();
boolean intentMe = (recipient == null) ? true : intendsMe(recipient);
if (!intentMe) {
LOG.warn("tid={}: I am not the intended recipient, but '{}'", tid, reqHeader.getRecipient());
failureCode = PKIFailureInfo.badRequest;
statusText = "I am not the intended recipient";
} else if (messageTime == null) {
if (cmpControl.isMessageTimeRequired()) {
failureCode = PKIFailureInfo.missingTimeStamp;
statusText = "missing time-stamp";
}
} else {
long messageTimeBias = cmpControl.getMessageTimeBias();
if (messageTimeBias < 0) {
messageTimeBias *= -1;
}
long msgTimeMs = messageTime.getTime();
long currentTimeMs = System.currentTimeMillis();
long bias = (msgTimeMs - currentTimeMs) / 1000L;
if (bias > messageTimeBias) {
failureCode = PKIFailureInfo.badTime;
statusText = "message time is in the future";
} else if (bias * -1 > messageTimeBias) {
failureCode = PKIFailureInfo.badTime;
statusText = "message too old";
}
}
if (failureCode != null) {
if (event != null) {
event.setLevel(AuditLevel.INFO);
event.setStatus(AuditStatus.FAILED);
event.addEventData(CaAuditConstants.NAME_message, statusText);
}
return buildErrorPkiMessage(tid, reqHeader, failureCode, statusText);
}
boolean isProtected = message.hasProtection();
CmpRequestorInfo requestor;
String errorStatus;
if (isProtected) {
try {
ProtectionVerificationResult verificationResult = verifyProtection(tidStr, message, cmpControl);
ProtectionResult pr = verificationResult.getProtectionResult();
switch(pr) {
case VALID:
errorStatus = null;
break;
case INVALID:
errorStatus = "request is protected by signature but invalid";
break;
case NOT_SIGNATURE_BASED:
errorStatus = "request is not protected by signature";
break;
case SENDER_NOT_AUTHORIZED:
errorStatus = "request is protected by signature but the requestor is not authorized";
break;
case SIGALGO_FORBIDDEN:
errorStatus = "request is protected by signature but the protection algorithm" + " is forbidden";
break;
default:
throw new RuntimeException("should not reach here, unknown ProtectionResult " + pr);
}
// end switch
requestor = (CmpRequestorInfo) verificationResult.getRequestor();
} catch (Exception ex) {
LogUtil.error(LOG, ex, "tid=" + tidStr + ": could not verify the signature");
errorStatus = "request has invalid signature based protection";
requestor = null;
}
} else if (tlsClientCert != null) {
boolean authorized = false;
requestor = getRequestor(reqHeader);
if (requestor != null) {
if (tlsClientCert.equals(requestor.getCert().getCert())) {
authorized = true;
}
}
if (authorized) {
errorStatus = null;
} else {
LOG.warn("tid={}: not authorized requestor (TLS client '{}')", tid, X509Util.getRfc4519Name(tlsClientCert.getSubjectX500Principal()));
errorStatus = "requestor (TLS client certificate) is not authorized";
}
} else {
errorStatus = "request has no protection";
requestor = null;
}
if (errorStatus != null) {
if (event != null) {
event.setLevel(AuditLevel.INFO);
event.setStatus(AuditStatus.FAILED);
event.addEventData(CaAuditConstants.NAME_message, errorStatus);
}
return buildErrorPkiMessage(tid, reqHeader, PKIFailureInfo.badMessageCheck, errorStatus);
}
PKIMessage resp = processPkiMessage0(pkiMessage, requestor, tid, message, msgId, event);
if (isProtected) {
resp = addProtection(resp, event);
} else {
// protected by TLS connection
}
return resp;
}
use of com.github.zhenwei.core.asn1.DEROctetString in project android_packages_apps_Settings by DirtyUnicorns.
the class CertInstallerHelper method isCa.
private boolean isCa(X509Certificate cert) {
try {
byte[] asn1EncodedBytes = cert.getExtensionValue("2.5.29.19");
if (asn1EncodedBytes == null) {
return false;
}
DEROctetString derOctetString = (DEROctetString) new ASN1InputStream(asn1EncodedBytes).readObject();
byte[] octets = derOctetString.getOctets();
ASN1Sequence sequence = (ASN1Sequence) new ASN1InputStream(octets).readObject();
return BasicConstraints.getInstance(sequence).isCA();
} catch (IOException e) {
return false;
}
}
use of com.github.zhenwei.core.asn1.DEROctetString in project android_packages_apps_Settings by crdroidandroid.
the class CertInstallerHelper method isCa.
private boolean isCa(X509Certificate cert) {
try {
byte[] asn1EncodedBytes = cert.getExtensionValue("2.5.29.19");
if (asn1EncodedBytes == null) {
return false;
}
DEROctetString derOctetString = (DEROctetString) new ASN1InputStream(asn1EncodedBytes).readObject();
byte[] octets = derOctetString.getOctets();
ASN1Sequence sequence = (ASN1Sequence) new ASN1InputStream(octets).readObject();
return BasicConstraints.getInstance(sequence).isCA();
} catch (IOException e) {
return false;
}
}
use of com.github.zhenwei.core.asn1.DEROctetString in project candlepin by candlepin.
the class BouncyCastlePKIUtility method createX509Certificate.
@Override
public X509Certificate createX509Certificate(String dn, Set<X509ExtensionWrapper> extensions, Set<X509ByteExtensionWrapper> byteExtensions, Date startDate, Date endDate, KeyPair clientKeyPair, BigInteger serialNumber, String alternateName) throws GeneralSecurityException, IOException {
X509Certificate caCert = reader.getCACert();
byte[] publicKeyEncoded = clientKeyPair.getPublic().getEncoded();
X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(X500Name.getInstance(caCert.getSubjectX500Principal().getEncoded()), serialNumber, startDate, endDate, new X500Name(dn), SubjectPublicKeyInfo.getInstance(publicKeyEncoded));
// set key usage - required for proper x509 function
KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment);
// add SSL extensions - required for proper x509 function
NetscapeCertType certType = new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime);
certGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, certType);
certGen.addExtension(Extension.keyUsage, false, keyUsage);
JcaX509ExtensionUtils extensionUtil = new JcaX509ExtensionUtils();
AuthorityKeyIdentifier aki = extensionUtil.createAuthorityKeyIdentifier(caCert);
certGen.addExtension(Extension.authorityKeyIdentifier, false, aki.getEncoded());
certGen.addExtension(Extension.subjectKeyIdentifier, false, subjectKeyWriter.getSubjectKeyIdentifier(clientKeyPair, extensions));
certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
// Add an additional alternative name if provided.
if (alternateName != null) {
/*
Why add the certificate subject again as an alternative name? RFC 6125 Section 6.4.4
stipulates that if SANs are provided, a validator MUST use them instead of the certificate
subject. If no SANs are present, the RFC allows the validator to use the subject field. So,
if we do have an SAN to add, we need to add the subject field again as an SAN.
See http://stackoverflow.com/questions/5935369 and
https://tools.ietf.org/html/rfc6125#section-6.4.4 and
NB: These extensions should *not* be marked critical since the subject field is not empty.
*/
GeneralName subject = new GeneralName(GeneralName.directoryName, dn);
GeneralName name = new GeneralName(GeneralName.directoryName, "CN=" + alternateName);
ASN1Encodable[] altNameArray = { subject, name };
GeneralNames altNames = GeneralNames.getInstance(new DERSequence(altNameArray));
certGen.addExtension(Extension.subjectAlternativeName, false, altNames);
}
if (extensions != null) {
for (X509ExtensionWrapper wrapper : extensions) {
// Bouncycastle hates null values. So, set them to blank
// if they are null
String value = wrapper.getValue() == null ? "" : wrapper.getValue();
certGen.addExtension(wrapper.toASN1Primitive(), wrapper.isCritical(), new DERUTF8String(value));
}
}
if (byteExtensions != null) {
for (X509ByteExtensionWrapper wrapper : byteExtensions) {
// Bouncycastle hates null values. So, set them to blank
// if they are null
byte[] value = wrapper.getValue() == null ? new byte[0] : wrapper.getValue();
certGen.addExtension(wrapper.toASN1Primitive(), wrapper.isCritical(), new DEROctetString(value));
}
}
JcaContentSignerBuilder builder = new JcaContentSignerBuilder(SIGNATURE_ALGO).setProvider(BC_PROVIDER);
ContentSigner signer;
try {
signer = builder.build(reader.getCaKey());
} catch (OperatorCreationException e) {
throw new IOException(e);
}
// Generate the certificate
return new JcaX509CertificateConverter().getCertificate(certGen.build(signer));
}
use of com.github.zhenwei.core.asn1.DEROctetString in project candlepin by candlepin.
the class BouncyCastlePKIUtility method decodeDERValue.
@Override
public String decodeDERValue(byte[] value) {
ASN1InputStream vis = null;
ASN1InputStream decoded = null;
try {
vis = new ASN1InputStream(value);
decoded = new ASN1InputStream(((DEROctetString) vis.readObject()).getOctets());
return decoded.readObject().toString();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (vis != null) {
try {
vis.close();
} catch (IOException e) {
log.warn("failed to close ASN1 stream", e);
}
}
if (decoded != null) {
try {
decoded.close();
} catch (IOException e) {
log.warn("failed to close ASN1 stream", e);
}
}
}
}
Aggregations