internal KeyTransRecipientInformation(KeyTransRecipientInfo info, CmsSecureReadable secureReadable) : base(info.KeyEncryptionAlgorithm, secureReadable) { this.info = info; rid = new RecipientID(); RecipientIdentifier recipientIdentifier = info.RecipientIdentifier; try { if (recipientIdentifier.IsTagged) { Asn1OctetString instance = Asn1OctetString.GetInstance(recipientIdentifier.ID); rid.SubjectKeyIdentifier = instance.GetOctets(); } else { Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber instance2 = Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber.GetInstance(recipientIdentifier.ID); rid.Issuer = instance2.Name; rid.SerialNumber = instance2.SerialNumber.Value; } } catch (IOException) { throw new ArgumentException("invalid rid in KeyTransRecipientInformation"); } }
public RecipientInformation this[RecipientID selector] { get { return(GetFirstRecipient(selector)); } }
internal KeyAgreeRecipientInformation(KeyAgreeRecipientInfo info, RecipientID rid, Asn1OctetString encryptedKey, CmsSecureReadable secureReadable) : base(info.KeyEncryptionAlgorithm, secureReadable) { this.info = info; base.rid = rid; this.encryptedKey = encryptedKey; }
internal static void ReadRecipientInfo(IList infos, KeyAgreeRecipientInfo info, CmsSecureReadable secureReadable) { try { foreach (Asn1Encodable recipientEncryptedKey in info.RecipientEncryptedKeys) { RecipientEncryptedKey instance = RecipientEncryptedKey.GetInstance(recipientEncryptedKey.ToAsn1Object()); RecipientID recipientID = new RecipientID(); KeyAgreeRecipientIdentifier identifier = instance.Identifier; Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber issuerAndSerialNumber = identifier.IssuerAndSerialNumber; if (issuerAndSerialNumber != null) { recipientID.Issuer = issuerAndSerialNumber.Name; recipientID.SerialNumber = issuerAndSerialNumber.SerialNumber.Value; } else { RecipientKeyIdentifier rKeyID = identifier.RKeyID; recipientID.SubjectKeyIdentifier = rKeyID.SubjectKeyIdentifier.GetOctets(); } infos.Add(new KeyAgreeRecipientInformation(info, recipientID, instance.EncryptedKey, secureReadable)); } } catch (IOException innerException) { throw new ArgumentException("invalid rid in KeyAgreeRecipientInformation", innerException); } }
internal KekRecipientInformation(KekRecipientInfo info, CmsSecureReadable secureReadable) : base(info.KeyEncryptionAlgorithm, secureReadable) { this.info = info; rid = new RecipientID(); KekIdentifier kekID = info.KekID; rid.KeyIdentifier = kekID.KeyIdentifier.GetOctets(); }
public ICollection GetRecipients(RecipientID selector) { IList list = (IList)table[selector]; if (list != null) { return(Platform.CreateArrayList(list)); } return(Platform.CreateArrayList()); }
public RecipientInformation GetFirstRecipient(RecipientID selector) { IList list = (IList)table[selector]; if (list != null) { return((RecipientInformation)list[0]); } return(null); }
public bool Equals(IMessage message) { bool one = RecipientID.Equals(message.RecipientID); bool two = SenderID.Equals(message.SenderID); bool three = Payload.Equals(message.Payload); if (RecipientID.Equals(message.RecipientID) && SenderID.Equals(message.SenderID) && Payload.Equals(message.Payload)) { return(true); } return(false); }
public RecipientInformationStore(ICollection recipientInfos) { foreach (RecipientInformation recipientInfo in recipientInfos) { RecipientID recipientID = recipientInfo.RecipientID; IList list = (IList)table[recipientID]; if (list == null) { list = (IList)(table[recipientID] = Platform.CreateArrayList(1)); } list.Add(recipientInfo); } all = Platform.CreateArrayList(recipientInfos); }
private static void ConfirmDataReceived(RecipientInformationStore recipients, byte[] expectedData, X509Certificate reciCert, AsymmetricKeyParameter reciPrivKey) { RecipientID rid = new RecipientID(); rid.Issuer = PrincipalUtilities.GetIssuerX509Principal(reciCert); rid.SerialNumber = reciCert.SerialNumber; RecipientInformation recipient = recipients[rid]; Assert.IsNotNull(recipient); byte[] actualData = recipient.GetContent(reciPrivKey); Assert.IsTrue(Arrays.AreEqual(expectedData, actualData)); }
/// <inheritdoc /> public byte[] Decrypt(byte[] data) { foreach (var pkcsStore in _allSenderCertificates) { var certAlias = pkcsStore.Aliases.Cast <string>().First(x => pkcsStore.IsKeyEntry(x)); var certEntry = pkcsStore.GetCertificate(certAlias); var cert = certEntry.Certificate; var envelopedData = new CmsEnvelopedData(data); var recepientInfos = envelopedData.GetRecipientInfos(); var recepientId = new RecipientID() { Issuer = cert.IssuerDN, SerialNumber = cert.SerialNumber }; var recepient = recepientInfos[recepientId]; if (recepient == null) { continue; } var privKeyEntry = pkcsStore.GetKey(certAlias); var privKey = privKeyEntry.Key; var decryptedData = recepient.GetContent(privKey); var sig = new CmsSignedData(decryptedData); var sigInfos = sig.GetSignerInfos(); var signerId = new SignerID() { Issuer = _receiverCertificate.IssuerDN, SerialNumber = _receiverCertificate.SerialNumber }; var signer = sigInfos.GetFirstSigner(signerId); if (!signer.Verify(_receiverCertificate)) { throw new ExtraEncryptionException("Failed to verify the signature."); } var verifiedData = new MemoryStream(); sig.SignedContent.Write(verifiedData); return(verifiedData.ToArray()); } throw new ExtraEncryptionException("No certificate for decryption found."); }
public override bool Equals(object obj) { if (obj == this) { return(true); } RecipientID recipientID = obj as RecipientID; if (recipientID == null) { return(false); } if (Arrays.AreEqual(keyIdentifier, recipientID.keyIdentifier) && Arrays.AreEqual(base.SubjectKeyIdentifier, recipientID.SubjectKeyIdentifier) && object.Equals(base.SerialNumber, recipientID.SerialNumber)) { return(X509CertStoreSelector.IssuersMatch(base.Issuer, recipientID.Issuer)); } return(false); }
public void TestTwoAesKek() { byte[] data = Encoding.ASCII.GetBytes("WallaWallaWashington"); KeyParameter kek1 = CmsTestUtil.MakeAes192Key(); KeyParameter kek2 = CmsTestUtil.MakeAes192Key(); CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator(); byte[] kekId1 = new byte[] { 1, 2, 3, 4, 5 }; byte[] kekId2 = new byte[] { 5, 4, 3, 2, 1 }; edGen.AddKekRecipient("AES192", kek1, kekId1); edGen.AddKekRecipient("AES192", kek2, kekId2); MemoryStream bOut = new MemoryStream(); Stream outStream = edGen.Open( bOut, CmsEnvelopedDataGenerator.DesEde3Cbc); outStream.Write(data, 0, data.Length); outStream.Close(); CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(bOut.ToArray()); RecipientInformationStore recipients = ep.GetRecipientInfos(); Assert.AreEqual(ep.EncryptionAlgOid, CmsEnvelopedDataGenerator.DesEde3Cbc); RecipientID recSel = new RecipientID(); recSel.KeyIdentifier = kekId2; RecipientInformation recipient = recipients.GetFirstRecipient(recSel); Assert.AreEqual(recipient.KeyEncryptionAlgOid, "2.16.840.1.101.3.4.1.25"); CmsTypedStream recData = recipient.GetContentStream(kek2); Assert.IsTrue(Arrays.AreEqual(data, CmsTestUtil.StreamToByteArray(recData.ContentStream))); ep.Close(); }
public void TestECKeyAgree() { byte[] data = Hex.Decode("504b492d4320434d5320456e76656c6f706564446174612053616d706c65"); CmsEnvelopedDataStreamGenerator edGen = new CmsEnvelopedDataStreamGenerator(); edGen.AddKeyAgreementRecipient( CmsEnvelopedDataGenerator.ECDHSha1Kdf, OrigECKP.Private, OrigECKP.Public, ReciECCert, CmsEnvelopedDataGenerator.Aes128Wrap); MemoryStream bOut = new MemoryStream(); Stream outStr = edGen.Open(bOut, CmsEnvelopedDataGenerator.Aes128Cbc); outStr.Write(data, 0, data.Length); outStr.Close(); CmsEnvelopedDataParser ep = new CmsEnvelopedDataParser(bOut.ToArray()); RecipientInformationStore recipients = ep.GetRecipientInfos(); Assert.AreEqual(ep.EncryptionAlgOid, CmsEnvelopedDataGenerator.Aes128Cbc); RecipientID recSel = new RecipientID(); // recSel.SetIssuer(PrincipalUtilities.GetIssuerX509Principal(ReciECCert).GetEncoded()); recSel.Issuer = PrincipalUtilities.GetIssuerX509Principal(ReciECCert); recSel.SerialNumber = ReciECCert.SerialNumber; RecipientInformation recipient = recipients.GetFirstRecipient(recSel); CmsTypedStream recData = recipient.GetContentStream(ReciECKP.Private); Assert.IsTrue(Arrays.AreEqual(data, CmsTestUtil.StreamToByteArray(recData.ContentStream))); ep.Close(); }
public void decode(Stream stream) { CmsEnvelopedDataParser cmsEnvelopedDataParser = new CmsEnvelopedDataParser(b); RecipientID recipientID = new RecipientID(); recipientID.SerialNumber = c.Certificate.SerialNumber; recipientID.Issuer = c.Certificate.IssuerDN; CmsTypedStream contentStream = cmsEnvelopedDataParser.GetRecipientInfos().GetFirstRecipient(recipientID).GetContentStream(d.Key); byte[] buffer = new byte[8192]; BufferedStream bufferedStream = new BufferedStream(contentStream.ContentStream, 8192); BufferedStream bufferedStream2 = new BufferedStream(stream, 8192); int count; while ((count = bufferedStream.Read(buffer, 0, 8192)) > 0) { bufferedStream2.Write(buffer, 0, count); } bufferedStream2.Flush(); bufferedStream.Close(); }
/** * Prepares everything to decrypt the document. * * @param encryption encryption dictionary, can be retrieved via * {@link Document#getEncryption()} * @param documentIDArray document id which is returned via * {@link org.apache.pdfbox.cos.COSDocument#getDocumentID()} (not used by * this handler) * @param decryptionMaterial Information used to decrypt the document. * * @throws IOException If there is an error accessing data. If verbose mode * is enabled, the exception message will provide more details why the * match wasn't successful. */ public override void PrepareForDecryption(PdfEncryption encryption, PdfArray documentIDArray, DecryptionMaterial decryptionMaterial) { if (!(decryptionMaterial is PublicKeyDecryptionMaterial)) { throw new IOException( "Provided decryption material is not compatible with the document"); } SetDecryptMetadata(encryption.IsEncryptMetaData); if (encryption.Length != 0) { this.keyLength = encryption.Length; } PublicKeyDecryptionMaterial material = (PublicKeyDecryptionMaterial)decryptionMaterial; try { bool foundRecipient = false; //Org.BouncyCastle.X509.Extension. X509Certificate certificate = material.Certificate; X509CertificateEntry materialCert = null; if (certificate != null) { materialCert = new X509CertificateEntry(certificate); } // the decrypted content of the enveloped data that match // the certificate in the decryption material provided byte[] envelopedData = null; // the bytes of each recipient in the recipients array PdfArray array = (PdfArray)encryption.BaseDataObject.Resolve(PdfName.Recipients); if (array == null) { PdfCryptFilterDictionary defaultCryptFilterDictionary = encryption.DefaultCryptFilterDictionary; array = (PdfArray)defaultCryptFilterDictionary.BaseDataObject.Resolve(PdfName.Recipients); } byte[][] recipientFieldsBytes = new byte[array.Count][]; //TODO encryption.getRecipientsLength() and getRecipientStringAt() should be deprecated int recipientFieldsLength = 0; StringBuilder extraInfo = new StringBuilder(); for (int i = 0; i < array.Count; i++) { PdfString recipientFieldString = (PdfString)array.Resolve(i); byte[] recipientBytes = recipientFieldString.GetBuffer(); CmsEnvelopedData data = new CmsEnvelopedData(recipientBytes); var recipCertificatesIt = data.GetRecipientInfos().GetRecipients(); int j = 0; foreach (RecipientInformation ri in recipCertificatesIt) { // Impl: if a matching certificate was previously found it is an error, // here we just don't care about it RecipientID rid = ri.RecipientID; if (!foundRecipient && rid.Match(materialCert)) { foundRecipient = true; var privateKey = material.PrivateKey; // might need to call setContentProvider() if we use PKI token, see // http://bouncy-castle.1462172.n4.nabble.com/CMSException-exception-unwrapping-key-key-invalid-unknown-key-type-passed-to-RSA-td4658109.html //DotNetUtilities.GetKeyPair(ri.AlgorithmIdentifier) envelopedData = ri.GetContent(privateKey.Key); break; } j++; if (certificate != null) { extraInfo.Append('\n'); extraInfo.Append(j); extraInfo.Append(": "); if (ri is KeyTransRecipientInformation) { appendCertInfo(extraInfo, (KeyTransRecipientInformation)ri, certificate, materialCert); } } } recipientFieldsBytes[i] = recipientBytes; recipientFieldsLength += recipientBytes.Length; } if (!foundRecipient || envelopedData == null) { throw new IOException("The certificate matches none of " + array.Count + " recipient entries" + extraInfo.ToString()); } if (envelopedData.Length != 24) { throw new IOException("The enveloped data does not contain 24 bytes"); } // now envelopedData contains: // - the 20 bytes seed // - the 4 bytes of permission for the current user byte[] accessBytes = new byte[4]; Array.Copy(envelopedData, 20, accessBytes, 0, 4); AccessPermission currentAccessPermission = new AccessPermission(accessBytes); currentAccessPermission.IsReadOnly = true; CurrentAccessPermission = currentAccessPermission; // what we will put in the SHA1 = the seed + each byte contained in the recipients array byte[] sha1Input = new byte[recipientFieldsLength + 20]; // put the seed in the sha1 input Array.Copy(envelopedData, 0, sha1Input, 0, 20); // put each bytes of the recipients array in the sha1 input int sha1InputOffset = 20; foreach (byte[] recipientFieldsByte in recipientFieldsBytes) { Array.Copy(recipientFieldsByte, 0, sha1Input, sha1InputOffset, recipientFieldsByte.Length); sha1InputOffset += recipientFieldsByte.Length; } byte[] mdResult; if (encryption.Version == 4 || encryption.Version == 5) { mdResult = SHA256.Create().Digest(sha1Input); // detect whether AES encryption is used. This assumes that the encryption algo is // stored in the PDCryptFilterDictionary // However, crypt filters are used only when V is 4 or 5. PdfCryptFilterDictionary defaultCryptFilterDictionary = encryption.DefaultCryptFilterDictionary; if (defaultCryptFilterDictionary != null) { PdfName cryptFilterMethod = defaultCryptFilterDictionary.CryptFilterMethod; IsAES = PdfName.AESV2.Equals(cryptFilterMethod) || PdfName.AESV3.Equals(cryptFilterMethod); } } else { mdResult = SHA1.Create().Digest(sha1Input); } // we have the encryption key ... encryptionKey = new byte[this.keyLength / 8]; Array.Copy(mdResult, 0, encryptionKey, 0, this.keyLength / 8); } catch (Exception e) { throw new IOException("", e); } }
/// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>An hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() { return(string.Concat("DocListFilteredCriteria", DocID.ToString(), DocClassID.ToString(), DocTypeID.ToString(), SenderID.ToString(), RecipientID.ToString(), DocRef.ToString(), DocDate.ToString(), Subject.ToString(), DocStatusID.ToString(), CreateDate.ToString(), CreateUserID.ToString(), ChangeDate.ToString(), ChangeUserID.ToString()).GetHashCode()); }
/// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { if (obj is DocListFilteredCriteria) { var c = (DocListFilteredCriteria)obj; if (!DocID.Equals(c.DocID)) { return(false); } if (!DocClassID.Equals(c.DocClassID)) { return(false); } if (!DocTypeID.Equals(c.DocTypeID)) { return(false); } if (!SenderID.Equals(c.SenderID)) { return(false); } if (!RecipientID.Equals(c.RecipientID)) { return(false); } if (!DocRef.Equals(c.DocRef)) { return(false); } if (!DocDate.Equals(c.DocDate)) { return(false); } if (!Subject.Equals(c.Subject)) { return(false); } if (!DocStatusID.Equals(c.DocStatusID)) { return(false); } if (!CreateDate.Equals(c.CreateDate)) { return(false); } if (!CreateUserID.Equals(c.CreateUserID)) { return(false); } if (!ChangeDate.Equals(c.ChangeDate)) { return(false); } if (!ChangeUserID.Equals(c.ChangeUserID)) { return(false); } return(true); } return(false); }
public MimeEntity DecryptEntity(byte[] encryptedBytes, X509Certificate2 decryptingCertificate) { try { if (decryptingCertificate == null) { throw new EncryptionException(EncryptionError.NoCertificates); } // TODO: introduce buffering if you are using large files // CMSEnvelopeData is a PKCS# structure rfc4134 var envelopedData = new CmsEnvelopedData(encryptedBytes); var envData = EnvelopedData.GetInstance(envelopedData.ContentInfo.Content); using (var session = GetSession()) { if (session == null) { return(null); } foreach (Asn1Sequence asn1Set in envData.RecipientInfos) { var recip = RecipientInfo.GetInstance(asn1Set); var keyTransRecipientInfo = KeyTransRecipientInfo.GetInstance(recip.Info); var sessionKey = Pkcs11Util.Decrypt(session, keyTransRecipientInfo, decryptingCertificate); #if DEBUG Console.WriteLine(Asn1Dump.DumpAsString(envData)); #endif if (sessionKey == null) { continue; } var recipientId = new RecipientID(); var issuerAndSerialNumber = (IssuerAndSerialNumber)keyTransRecipientInfo.RecipientIdentifier.ID; recipientId.Issuer = issuerAndSerialNumber.Name; recipientId.SerialNumber = issuerAndSerialNumber.SerialNumber.Value; var recipientInformation = envelopedData.GetRecipientInfos().GetRecipients(recipientId); var recipients = new ArrayList(recipientInformation); // // read the encrypted content info // var encInfo = envData.EncryptedContentInfo; var encAlg = encInfo.ContentEncryptionAlgorithm; var readable = new CmsProcessableByteArray(encInfo.EncryptedContent.GetOctets()); var keyParameter = ParameterUtilities.CreateKeyParameter(encAlg.Algorithm.Id, sessionKey); // Todo: does this work with multi recipient? foreach (RecipientInformation recipient in recipients) { var cmsReadable = GetReadable(keyParameter, encAlg, readable); var cmsTypedStream = new CmsTypedStream(cmsReadable.GetInputStream()); var contentBytes = StreamToByteArray(cmsTypedStream.ContentStream); var mimeEntity = MimeSerializer.Default.Deserialize <MimeEntity>(contentBytes); return(mimeEntity); } } } } catch (Exception ex) { Error.NotifyEvent(this, ex); } return(null); }
public static byte[] ExtractSignerId(this RecipientID selector) { //In case of a Recipient it seems to be raw return(selector.SubjectKeyIdentifier); }
internal PasswordRecipientInformation(PasswordRecipientInfo info, CmsSecureReadable secureReadable) : base(info.KeyEncryptionAlgorithm, secureReadable) { this.info = info; rid = new RecipientID(); }