public bool verify(AsymmetricKeyParameter key) { try { if (!this.isSigned()) { throw new OCSPException("attempt to verify signature on unsigned object"); } // ------------------------------------------------------------- Signer sig = SignerUtil.getSigner(this.getSignatureAlgOID()); // The above may not work as not sure if key is dotted decimal oid as string or an ALG mechanism name. // ------------------------------------------------------------- sig.init(false, key); MemoryStream mStr = new MemoryStream(); ASN1OutputStream aOut = new ASN1OutputStream(mStr); aOut.writeObject(req.getTbsRequest()); byte[] b = mStr.ToArray(); sig.update(b, 0, b.Length); return(sig.verifySignature(this.getSignature())); } catch (Exception e) { throw new OCSPException("exception processing sig: " + e, e); } }
/** * When using authenticatedAttributes the authentication process is different. * The document digest is generated and put inside the attribute. The signing is done over the DER encoded * authenticatedAttributes. This method provides that encoding and the parameters must be * exactly the same as in {@link #getEncodedPKCS7(byte[],Calendar)}. * <p> * A simple example: * <p> * <pre> * Calendar cal = Calendar.getInstance(); * PdfPKCS7 pk7 = new PdfPKCS7(key, chain, null, "SHA1", null, false); * MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); * byte buf[] = new byte[8192]; * int n; * Stream inp = sap.getRangeStream(); * while ((n = inp.read(buf)) > 0) { * messageDigest.update(buf, 0, n); * } * byte hash[] = messageDigest.digest(); * byte sh[] = pk7.getAuthenticatedAttributeBytes(hash, cal); * pk7.update(sh, 0, sh.length); * byte sg[] = pk7.getEncodedPKCS7(hash, cal); * </pre> * @param secondDigest the content digest * @param signingTime the signing time * @return the byte array representation of the authenticatedAttributes ready to be signed */ public byte[] GetAuthenticatedAttributeBytes(byte[] secondDigest, DateTime signingTime) { ASN1EncodableVector attribute = new ASN1EncodableVector(); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(ID_CONTENT_TYPE)); v.add(new DERSet(new DERObjectIdentifier(ID_PKCS7_DATA))); attribute.add(new DERSequence(v)); v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(ID_SIGNING_TIME)); v.add(new DERSet(new DERUTCTime(signingTime))); attribute.add(new DERSequence(v)); v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(ID_MESSAGE_DIGEST)); v.add(new DERSet(new DEROctetString(secondDigest))); attribute.add(new DERSequence(v)); MemoryStream bOut = new MemoryStream(); ASN1OutputStream dout = new ASN1OutputStream(bOut); dout.writeObject(new DERSet(attribute)); dout.Close(); return(bOut.ToArray()); }
public byte[] getEncoded() { MemoryStream mStr = new MemoryStream(); ASN1OutputStream aOut = new ASN1OutputStream(mStr); aOut.writeObject(req); return(mStr.ToArray()); }
/// <summary> /// Return a the DER encoded response. /// </summary> /// <returns>A byte array.</returns> public byte[] getEncoded() { MemoryStream bOut = new MemoryStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); aOut.writeObject(resp); return(bOut.ToArray()); }
/// <summary> /// Create an System.Security.Cryptography.X509Certificate from an X509Certificate Structure. /// </summary> /// <param name="x509struct"></param> /// <returns>An System.Security.Cryptography.X509Certificate.</returns> public static System.Security.Cryptography.X509Certificates.X509Certificate toX509Certificate(X509CertificateStructure x509struct) { MemoryStream mStr = new MemoryStream(); ASN1OutputStream aOut = new ASN1OutputStream(mStr); aOut.writeObject(x509struct); aOut.Flush(); mStr.Seek(0, 0); return(new System.Security.Cryptography.X509Certificates.X509Certificate(mStr.ToArray())); }
/** * Gets the bytes for the PKCS#1 object. * @return a byte array */ public byte[] GetEncodedPKCS1() { if (externalDigest != null) { digest = externalDigest; } else { digest = sig.generateSignature(); } MemoryStream bOut = new MemoryStream(); ASN1OutputStream dout = new ASN1OutputStream(bOut); dout.writeObject(new DEROctetString(digest)); dout.Close(); return(bOut.ToArray()); }
/** * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes * in the signerInfo can also be set. If either of the parameters is <CODE>null</CODE>, none will be used. * @param secondDigest the digest in the authenticatedAttributes * @param signingTime the signing time in the authenticatedAttributes * @return the bytes for the PKCS7SignedData object */ public byte[] GetEncodedPKCS7(byte[] secondDigest, DateTime signingTime) { if (externalDigest != null) { digest = externalDigest; if (RSAdata != null) { RSAdata = externalRSAdata; } } else if (externalRSAdata != null && RSAdata != null) { RSAdata = externalRSAdata; sig.update(RSAdata, 0, RSAdata.Length); digest = sig.generateSignature(); } else { if (RSAdata != null) { RSAdata = new byte[messageDigest.getDigestSize()]; messageDigest.doFinal(RSAdata, 0); sig.update(RSAdata, 0, RSAdata.Length); } digest = sig.generateSignature(); } // Create the set of Hash algorithms ASN1EncodableVector digestAlgorithms = new ASN1EncodableVector(); foreach (string dal in digestalgos.Keys) { ASN1EncodableVector algos = new ASN1EncodableVector(); algos.add(new DERObjectIdentifier(dal)); algos.add(new DERNull()); digestAlgorithms.add(new DERSequence(algos)); } // Create the contentInfo. ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(ID_PKCS7_DATA)); if (RSAdata != null) { v.add(new DERTaggedObject(0, new DEROctetString(RSAdata))); } DERSequence contentinfo = new DERSequence(v); // Get all the certificates // v = new ASN1EncodableVector(); foreach (X509Certificate xcert in certs) { ASN1InputStream tempstream = new ASN1InputStream(new MemoryStream(xcert.getEncoded())); v.add(tempstream.readObject()); } DERSet dercertificates = new DERSet(v); // Create signerinfo structure. // ASN1EncodableVector signerinfo = new ASN1EncodableVector(); // Add the signerInfo version // signerinfo.add(new DERInteger(signerversion)); v = new ASN1EncodableVector(); v.add(GetIssuer(signCert.getTBSCertificate())); v.add(new DERInteger(signCert.getSerialNumber())); signerinfo.add(new DERSequence(v)); // Add the digestAlgorithm v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(digestAlgorithm)); v.add(new DERNull()); signerinfo.add(new DERSequence(v)); // add the authenticated attribute if present if (secondDigest != null /*&& signingTime != null*/) { ASN1EncodableVector attribute = new ASN1EncodableVector(); v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(ID_CONTENT_TYPE)); v.add(new DERSet(new DERObjectIdentifier(ID_PKCS7_DATA))); attribute.add(new DERSequence(v)); v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(ID_SIGNING_TIME)); v.add(new DERSet(new DERUTCTime(signingTime))); attribute.add(new DERSequence(v)); v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(ID_MESSAGE_DIGEST)); v.add(new DERSet(new DEROctetString(secondDigest))); attribute.add(new DERSequence(v)); signerinfo.add(new DERTaggedObject(false, 0, new DERSet(attribute))); } // Add the digestEncryptionAlgorithm v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier(digestEncryptionAlgorithm)); v.add(new DERNull()); signerinfo.add(new DERSequence(v)); // Add the digest signerinfo.add(new DEROctetString(digest)); // Finally build the body out of all the components above ASN1EncodableVector body = new ASN1EncodableVector(); body.add(new DERInteger(version)); body.add(new DERSet(digestAlgorithms)); body.add(contentinfo); body.add(new DERTaggedObject(false, 0, dercertificates)); // if (crls.Count > 0) { // v = new ASN1EncodableVector(); // for (Iterator i = crls.iterator();i.hasNext();) { // ASN1InputStream t = new ASN1InputStream(new ByteArrayInputStream((((X509CRL)i.next()).getEncoded()))); // v.add(t.readObject()); // } // DERSet dercrls = new DERSet(v); // body.add(new DERTaggedObject(false, 1, dercrls)); // } // Only allow one signerInfo body.add(new DERSet(new DERSequence(signerinfo))); // Now we have the body, wrap it in it's PKCS7Signed shell // and return it // ASN1EncodableVector whole = new ASN1EncodableVector(); whole.add(new DERObjectIdentifier(ID_PKCS7_SIGNED_DATA)); whole.add(new DERTaggedObject(0, new DERSequence(body))); MemoryStream bOut = new MemoryStream(); ASN1OutputStream dout = new ASN1OutputStream(bOut); dout.writeObject(new DERSequence(whole)); dout.Close(); return(bOut.ToArray()); }
/** * Verifies a signature using the sub-filter adbe.pkcs7.detached or * adbe.pkcs7.sha1. * @param contentsKey the /Contents key * @param provider the provider or <code>null</code> for the default provider * @throws SecurityException on error * @throws CRLException on error * @throws InvalidKeyException on error * @throws CertificateException on error * @throws NoSuchProviderException on error * @throws NoSuchAlgorithmException on error */ public PdfPKCS7(byte[] contentsKey) { ASN1InputStream din = new ASN1InputStream(new MemoryStream(contentsKey)); // // Basic checks to make sure it's a PKCS#7 SignedData Object // ASN1Object pkcs; try { pkcs = din.readObject(); } catch { throw new ArgumentException("can't decode PKCS7SignedData object"); } if (!(pkcs is ASN1Sequence)) { throw new ArgumentException("Not a valid PKCS#7 object - not a sequence"); } ASN1Sequence signedData = (ASN1Sequence)pkcs; DERObjectIdentifier objId = (DERObjectIdentifier)signedData.getObjectAt(0); if (!objId.getId().Equals(ID_PKCS7_SIGNED_DATA)) { throw new ArgumentException("Not a valid PKCS#7 object - not signed data"); } ASN1Sequence content = (ASN1Sequence)((DERTaggedObject)signedData.getObjectAt(1)).getObject(); // the positions that we care are: // 0 - version // 1 - digestAlgorithms // 2 - possible ID_PKCS7_DATA // (the certificates and crls are taken out by other means) // last - signerInfos // the version version = ((DERInteger)content.getObjectAt(0)).getValue().intValue(); // the digestAlgorithms digestalgos = new Hashtable(); IEnumerator e = ((ASN1Set)content.getObjectAt(1)).getObjects(); while (e.MoveNext()) { ASN1Sequence s = (ASN1Sequence)e.Current; DERObjectIdentifier o = (DERObjectIdentifier)s.getObjectAt(0); digestalgos[o.getId()] = null; } // the certificates and crls X509CertificateParser cf = new X509CertificateParser(contentsKey); certs = new ArrayList(); while (true) { X509Certificate cc = cf.ReadCertificate(); if (cc == null) { break; } certs.Add(cc); } crls = new ArrayList(); // the possible ID_PKCS7_DATA ASN1Sequence rsaData = (ASN1Sequence)content.getObjectAt(2); if (rsaData.size() > 1) { DEROctetString rsaDataContent = (DEROctetString)((DERTaggedObject)rsaData.getObjectAt(1)).getObject(); RSAdata = rsaDataContent.getOctets(); } // the signerInfos int next = 3; while (content.getObjectAt(next) is DERTaggedObject) { ++next; } ASN1Set signerInfos = (ASN1Set)content.getObjectAt(next); if (signerInfos.size() != 1) { throw new ArgumentException("This PKCS#7 object has multiple SignerInfos - only one is supported at this time"); } ASN1Sequence signerInfo = (ASN1Sequence)signerInfos.getObjectAt(0); // the positions that we care are // 0 - version // 1 - the signing certificate serial number // 2 - the digest algorithm // 3 or 4 - digestEncryptionAlgorithm // 4 or 5 - encryptedDigest signerversion = ((DERInteger)signerInfo.getObjectAt(0)).getValue().intValue(); // Get the signing certificate ASN1Sequence issuerAndSerialNumber = (ASN1Sequence)signerInfo.getObjectAt(1); BigInteger serialNumber = ((DERInteger)issuerAndSerialNumber.getObjectAt(1)).getValue(); foreach (X509Certificate cert in certs) { if (serialNumber.Equals(cert.getSerialNumber())) { signCert = cert; break; } } if (signCert == null) { throw new ArgumentException("Can't find signing certificate with serial " + serialNumber.ToString(16)); } digestAlgorithm = ((DERObjectIdentifier)((ASN1Sequence)signerInfo.getObjectAt(2)).getObjectAt(0)).getId(); next = 3; if (signerInfo.getObjectAt(next) is ASN1TaggedObject) { ASN1TaggedObject tagsig = (ASN1TaggedObject)signerInfo.getObjectAt(next); ASN1Sequence sseq = (ASN1Sequence)tagsig.getObject(); MemoryStream bOut = new MemoryStream(); ASN1OutputStream dout = new ASN1OutputStream(bOut); try { ASN1EncodableVector attribute = new ASN1EncodableVector(); for (int k = 0; k < sseq.size(); ++k) { attribute.add(sseq.getObjectAt(k)); } dout.writeObject(new DERSet(attribute)); dout.Close(); } catch (IOException) {} sigAttr = bOut.ToArray(); for (int k = 0; k < sseq.size(); ++k) { ASN1Sequence seq2 = (ASN1Sequence)sseq.getObjectAt(k); if (((DERObjectIdentifier)seq2.getObjectAt(0)).getId().Equals(ID_MESSAGE_DIGEST)) { ASN1Set sset = (ASN1Set)seq2.getObjectAt(1); digestAttr = ((DEROctetString)sset.getObjectAt(0)).getOctets(); break; } } if (digestAttr == null) { throw new ArgumentException("Authenticated attribute is missing the digest."); } ++next; } digestEncryptionAlgorithm = ((DERObjectIdentifier)((ASN1Sequence)signerInfo.getObjectAt(next++)).getObjectAt(0)).getId(); digest = ((DEROctetString)signerInfo.getObjectAt(next)).getOctets(); if (RSAdata != null || digestAttr != null) { messageDigest = GetHashClass(); } sig = SignerUtil.getSigner(GetDigestAlgorithm()); sig.init(false, signCert.getPublicKey()); }
private OCSPReq generateRequest(DERObjectIdentifier signingAlgorithm, AsymmetricKeyParameter key, X509Certificate[] chain, SecureRandom random) { IEnumerator it = list.GetEnumerator(); ASN1EncodableVector requests = new ASN1EncodableVector(); Signature signature = null; while (it.MoveNext()) { requests.add(((RequestObject)it.Current).toRequest()); } TBSRequest tbsReq = new TBSRequest(requestorName, new DERSequence(requests), requestExtensions); Signer sig = null; if (signingAlgorithm != null) { try { sig = SignerUtil.getSigner(signingAlgorithm.getId()); if (random != null) { sig.init(true, new ParametersWithRandom(key, random)); } else { sig.init(true, key); } } catch (Exception e) { throw new OCSPException("exception creating signature: " + e.Message, e); } DERBitString bitSig = null; try { MemoryStream bOut = new MemoryStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); aOut.writeObject(tbsReq); byte[] b = bOut.ToArray(); sig.update(b, 0, b.Length); bitSig = new DERBitString(sig.generateSignature()); } catch (Exception e) { throw new OCSPException("exception processing TBSRequest: " + e.Message, e); } AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(signingAlgorithm, new DERNull()); if (chain != null && chain.Length > 0) { ASN1EncodableVector v = new ASN1EncodableVector(); try { for (int i = 0; i != chain.Length; i++) { v.add(new X509CertificateStructure((ASN1Sequence)makeObj(chain[i].getEncoded()))); } } catch (Exception e) { throw new OCSPException("error processing certs", e); } signature = new Signature(sigAlgId, bitSig, new DERSequence(v)); } else { signature = new Signature(sigAlgId, bitSig); } } return(new OCSPReq(new OCSPRequest(tbsReq, signature))); }