use of com.github.zhenwei.core.asn1.ocsp.Request in project LinLong-Java by zhenwei1108.
the class MiscPEMGenerator method createPemObject.
private PemObject createPemObject(Object o) throws IOException {
String type;
byte[] encoding;
if (o instanceof PemObject) {
return (PemObject) o;
}
if (o instanceof PemObjectGenerator) {
return ((PemObjectGenerator) o).generate();
}
if (o instanceof X509CertificateHolder) {
type = "CERTIFICATE";
encoding = ((X509CertificateHolder) o).getEncoded();
} else if (o instanceof X509CRLHolder) {
type = "X509 CRL";
encoding = ((X509CRLHolder) o).getEncoded();
} else if (o instanceof X509TrustedCertificateBlock) {
type = "TRUSTED CERTIFICATE";
encoding = ((X509TrustedCertificateBlock) o).getEncoded();
} else if (o instanceof PrivateKeyInfo) {
PrivateKeyInfo info = (PrivateKeyInfo) o;
ASN1ObjectIdentifier algOID = info.getPrivateKeyAlgorithm().getAlgorithm();
if (algOID.equals(PKCSObjectIdentifiers.rsaEncryption)) {
type = "RSA PRIVATE KEY";
encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
} else if (algOID.equals(dsaOids[0]) || algOID.equals(dsaOids[1])) {
type = "DSA PRIVATE KEY";
DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new ASN1Integer(0));
v.add(new ASN1Integer(p.getP()));
v.add(new ASN1Integer(p.getQ()));
v.add(new ASN1Integer(p.getG()));
BigInteger x = ASN1Integer.getInstance(info.parsePrivateKey()).getValue();
BigInteger y = p.getG().modPow(x, p.getP());
v.add(new ASN1Integer(y));
v.add(new ASN1Integer(x));
encoding = new DERSequence(v).getEncoded();
} else if (algOID.equals(X9ObjectIdentifiers.id_ecPublicKey)) {
type = "EC PRIVATE KEY";
encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
} else {
type = "PRIVATE KEY";
encoding = info.getEncoded();
}
} else if (o instanceof SubjectPublicKeyInfo) {
type = "PUBLIC KEY";
encoding = ((SubjectPublicKeyInfo) o).getEncoded();
} else if (o instanceof X509AttributeCertificateHolder) {
type = "ATTRIBUTE CERTIFICATE";
encoding = ((X509AttributeCertificateHolder) o).getEncoded();
} else if (o instanceof com.github.zhenwei.pkix.pkcs.PKCS10CertificationRequest) {
type = "CERTIFICATE REQUEST";
encoding = ((PKCS10CertificationRequest) o).getEncoded();
} else if (o instanceof PKCS8EncryptedPrivateKeyInfo) {
type = "ENCRYPTED PRIVATE KEY";
encoding = ((PKCS8EncryptedPrivateKeyInfo) o).getEncoded();
} else if (o instanceof ContentInfo) {
type = "PKCS7";
encoding = ((ContentInfo) o).getEncoded();
} else {
throw new PemGenerationException("unknown object passed - can't encode.");
}
if (encryptor != null) {
String dekAlgName = Strings.toUpperCase(encryptor.getAlgorithm());
// Note: For backward compatibility
if (dekAlgName.equals("DESEDE")) {
dekAlgName = "DES-EDE3-CBC";
}
byte[] iv = encryptor.getIV();
byte[] encData = encryptor.encrypt(encoding);
List headers = new ArrayList(2);
headers.add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
headers.add(new PemHeader("DEK-Info", dekAlgName + "," + getHexEncoded(iv)));
return new PemObject(type, headers, encData);
}
return new PemObject(type, encoding);
}
use of com.github.zhenwei.core.asn1.ocsp.Request in project LinLong-Java by zhenwei1108.
the class TimeStampRequest method validate.
/**
* Validate the timestamp request, checking the digest to see if it is of an accepted type and
* whether it is of the correct length for the algorithm specified.
*
* @param algorithms a set of OIDs giving accepted algorithms.
* @param policies if non-null a set of policies OIDs we are willing to sign under.
* @param extensions if non-null a set of extensions OIDs we are willing to accept.
* @throws TSPException if the request is invalid, or processing fails.
*/
public void validate(Set algorithms, Set policies, Set extensions) throws TSPException {
algorithms = convert(algorithms);
policies = convert(policies);
extensions = convert(extensions);
if (!algorithms.contains(this.getMessageImprintAlgOID())) {
throw new TSPValidationException("request contains unknown algorithm", PKIFailureInfo.badAlg);
}
if (policies != null && this.getReqPolicy() != null && !policies.contains(this.getReqPolicy())) {
throw new TSPValidationException("request contains unknown policy", PKIFailureInfo.unacceptedPolicy);
}
if (this.getExtensions() != null && extensions != null) {
Enumeration en = this.getExtensions().oids();
while (en.hasMoreElements()) {
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) en.nextElement();
if (!extensions.contains(oid)) {
throw new TSPValidationException("request contains unknown extension", PKIFailureInfo.unacceptedExtension);
}
}
}
int digestLength = TSPUtil.getDigestLength(this.getMessageImprintAlgOID().getId());
if (digestLength != this.getMessageImprintDigest().length) {
throw new TSPValidationException("imprint digest the wrong length", PKIFailureInfo.badDataFormat);
}
}
use of com.github.zhenwei.core.asn1.ocsp.Request in project LinLong-Java by zhenwei1108.
the class TimeStampResponseGenerator method generateGrantedResponse.
/**
* Return a granted response, if the passed in request passes validation with the passed in status
* string and extra extensions.
* <p>
* If genTime is null a timeNotAvailable or a validation exception occurs a TSPValidationException
* will be thrown. The parent TSPException will only occur on some sort of system failure.
* </p>
*
* @param request the request this response is for.
* @param serialNumber serial number for the response token.
* @param genTime generation time for the response token.
* @param additionalExtensions extra extensions to be added to the response token.
* @return the TimeStampResponse with a status of PKIStatus.GRANTED
* @throws TSPException on validation exception or internal error.
*/
public TimeStampResponse generateGrantedResponse(TimeStampRequest request, BigInteger serialNumber, Date genTime, String statusString, Extensions additionalExtensions) throws TSPException {
if (genTime == null) {
throw new TSPValidationException("The time source is not available.", PKIFailureInfo.timeNotAvailable);
}
request.validate(acceptedAlgorithms, acceptedPolicies, acceptedExtensions);
status = PKIStatus.GRANTED;
statusStrings = new ASN1EncodableVector();
if (statusString != null) {
this.addStatusString(statusString);
}
PKIStatusInfo pkiStatusInfo = getPKIStatusInfo();
ContentInfo tstTokenContentInfo;
try {
tstTokenContentInfo = tokenGenerator.generate(request, serialNumber, genTime, additionalExtensions).toCMSSignedData().toASN1Structure();
} catch (TSPException e) {
throw e;
} catch (Exception e) {
throw new TSPException("Timestamp token received cannot be converted to ContentInfo", e);
}
try {
return new TimeStampResponse(new DLSequence(new ASN1Encodable[] { pkiStatusInfo.toASN1Primitive(), tstTokenContentInfo.toASN1Primitive() }));
} catch (IOException e) {
throw new TSPException("created badly formatted response!");
}
}
use of com.github.zhenwei.core.asn1.ocsp.Request in project xipki by xipki.
the class OcspRequest method getInstance.
public static OcspRequest getInstance(OCSPRequest req) throws EncodingException {
TBSRequest tbsReq0 = req.getTbsRequest();
org.bouncycastle.asn1.x509.Extensions extensions0 = tbsReq0.getRequestExtensions();
Set<String> criticalExtensionOids = new HashSet<>();
if (extensions0 != null) {
for (ASN1ObjectIdentifier oid : extensions0.getCriticalExtensionOIDs()) {
criticalExtensionOids.add(oid.getId());
}
}
ASN1Sequence requestList0 = tbsReq0.getRequestList();
final int n = requestList0.size();
List<CertID> requestList = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
Request singleReq0 = Request.getInstance(requestList0.getObjectAt(i));
org.bouncycastle.asn1.ocsp.CertID certId0 = singleReq0.getReqCert();
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
out.write(certId0.getHashAlgorithm().getEncoded());
out.write(certId0.getIssuerNameHash().getEncoded());
out.write(certId0.getIssuerKeyHash().getEncoded());
} catch (IOException ex) {
throw new EncodingException(ex.getMessage(), ex);
}
byte[] encodedIssuer = out.toByteArray();
RequestIssuer issuer = new RequestIssuer(encodedIssuer, 0, encodedIssuer.length);
CertID certId = new CertID(issuer, certId0.getSerialNumber().getValue());
requestList.add(certId);
}
List<ExtendedExtension> extensions = new LinkedList<>();
if (extensions0 != null) {
ASN1ObjectIdentifier[] extOids = extensions0.getExtensionOIDs();
for (ASN1ObjectIdentifier oid : extOids) {
org.bouncycastle.asn1.x509.Extension extension0 = extensions0.getExtension(oid);
byte[] encoded;
try {
encoded = extension0.getEncoded();
} catch (IOException ex) {
throw new EncodingException("error encoding Extension", ex);
}
extensions.add(ExtendedExtension.getInstance(encoded, 0, encoded.length));
}
}
return new OcspRequest(tbsReq0.getVersion().getValue().intValue(), requestList, extensions);
}
use of com.github.zhenwei.core.asn1.ocsp.Request in project xipki by xipki.
the class AbstractOcspRequestor method ask.
@Override
public OCSPResp ask(X509Cert issuerCert, BigInteger[] serialNumbers, URL responderUrl, RequestOptions requestOptions, ReqRespDebug debug) throws OcspResponseException, OcspRequestorException {
notNull(issuerCert, "issuerCert");
notNull(requestOptions, "requestOptions");
notNull(responderUrl, "responderUrl");
byte[] nonce = null;
if (requestOptions.isUseNonce()) {
nonce = nextNonce(requestOptions.getNonceLen());
}
OCSPRequest ocspReq = buildRequest(issuerCert, serialNumbers, nonce, requestOptions);
byte[] encodedReq;
try {
encodedReq = ocspReq.getEncoded();
} catch (IOException ex) {
throw new OcspRequestorException("could not encode OCSP request: " + ex.getMessage(), ex);
}
ReqRespPair msgPair = null;
if (debug != null) {
msgPair = new ReqRespPair();
debug.add(msgPair);
if (debug.saveRequest()) {
msgPair.setRequest(encodedReq);
}
}
byte[] encodedResp;
try {
encodedResp = send(encodedReq, responderUrl, requestOptions);
} catch (IOException ex) {
throw new OcspResponseException.ResponderUnreachable("IOException: " + ex.getMessage(), ex);
}
if (msgPair != null && debug.saveResponse()) {
msgPair.setResponse(encodedResp);
}
OCSPResp ocspResp;
try {
ocspResp = new OCSPResp(encodedResp);
} catch (IOException ex) {
throw new OcspResponseException.InvalidResponse("IOException: " + ex.getMessage(), ex);
}
Object respObject;
try {
respObject = ocspResp.getResponseObject();
} catch (OCSPException ex) {
throw new OcspResponseException.InvalidResponse("responseObject is invalid");
}
if (ocspResp.getStatus() != 0) {
return ocspResp;
}
if (!(respObject instanceof BasicOCSPResp)) {
return ocspResp;
}
BasicOCSPResp basicOcspResp = (BasicOCSPResp) respObject;
if (nonce != null) {
Extension nonceExtn = basicOcspResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
if (nonceExtn == null) {
if (!requestOptions.isAllowNoNonceInResponse()) {
throw new OcspResponseException.OcspNonceUnmatched(nonce, null);
}
} else {
byte[] receivedNonce = nonceExtn.getExtnValue().getOctets();
if (!Arrays.equals(nonce, receivedNonce)) {
throw new OcspResponseException.OcspNonceUnmatched(nonce, receivedNonce);
}
}
}
SingleResp[] singleResponses = basicOcspResp.getResponses();
if (singleResponses == null || singleResponses.length == 0) {
String msg = StringUtil.concat("response with no singleResponse is returned, expected is ", Integer.toString(serialNumbers.length));
throw new OcspResponseException.OcspTargetUnmatched(msg);
}
final int countSingleResponses = singleResponses.length;
if (countSingleResponses != serialNumbers.length) {
String msg = StringUtil.concat("response with ", Integer.toString(countSingleResponses), " singleResponse", (countSingleResponses > 1 ? "s" : ""), " is returned, expected is ", Integer.toString(serialNumbers.length));
throw new OcspResponseException.OcspTargetUnmatched(msg);
}
Request reqAt0 = Request.getInstance(ocspReq.getTbsRequest().getRequestList().getObjectAt(0));
CertID certId = reqAt0.getReqCert();
ASN1ObjectIdentifier issuerHashAlg = certId.getHashAlgorithm().getAlgorithm();
byte[] issuerKeyHash = certId.getIssuerKeyHash().getOctets();
byte[] issuerNameHash = certId.getIssuerNameHash().getOctets();
if (serialNumbers.length == 1) {
SingleResp singleResp = singleResponses[0];
CertificateID cid = singleResp.getCertID();
boolean issuerMatch = issuerHashAlg.equals(cid.getHashAlgOID()) && Arrays.equals(issuerKeyHash, cid.getIssuerKeyHash()) && Arrays.equals(issuerNameHash, cid.getIssuerNameHash());
if (!issuerMatch) {
throw new OcspResponseException.OcspTargetUnmatched("the issuer is not requested");
}
BigInteger serialNumber = cid.getSerialNumber();
if (!serialNumbers[0].equals(serialNumber)) {
throw new OcspResponseException.OcspTargetUnmatched("the serialNumber is not requested");
}
} else {
List<BigInteger> tmpSerials1 = Arrays.asList(serialNumbers);
List<BigInteger> tmpSerials2 = new ArrayList<>(tmpSerials1);
for (int i = 0; i < countSingleResponses; i++) {
SingleResp singleResp = singleResponses[i];
CertificateID cid = singleResp.getCertID();
boolean issuerMatch = issuerHashAlg.equals(cid.getHashAlgOID()) && Arrays.equals(issuerKeyHash, cid.getIssuerKeyHash()) && Arrays.equals(issuerNameHash, cid.getIssuerNameHash());
if (!issuerMatch) {
throw new OcspResponseException.OcspTargetUnmatched("the issuer specified in singleResponse[" + i + "] is not requested");
}
BigInteger serialNumber = cid.getSerialNumber();
if (!tmpSerials2.remove(serialNumber)) {
if (tmpSerials1.contains(serialNumber)) {
throw new OcspResponseException.OcspTargetUnmatched("serialNumber " + LogUtil.formatCsn(serialNumber) + "is contained in at least two singleResponses");
} else {
throw new OcspResponseException.OcspTargetUnmatched("serialNumber " + LogUtil.formatCsn(serialNumber) + " specified in singleResponse[" + i + "] is not requested");
}
}
}
// end for
}
return ocspResp;
}
Aggregations