private ASN1 SubjectPublicKeyInfo() { ASN1 aSN = new ASN1(48); if (aa is RSA) { aSN.Add(PKCS7.AlgorithmIdentifier("1.2.840.113549.1.1.1")); RSAParameters rSAParameters = (aa as RSA).ExportParameters(includePrivateParameters: false); ASN1 aSN2 = new ASN1(48); aSN2.Add(ASN1Convert.FromUnsignedBigInteger(rSAParameters.Modulus)); aSN2.Add(ASN1Convert.FromUnsignedBigInteger(rSAParameters.Exponent)); aSN.Add(new ASN1(UniqueIdentifier(aSN2.GetBytes()))); } else { if (!(aa is DSA)) { throw new NotSupportedException("Unknown Asymmetric Algorithm " + aa.ToString()); } DSAParameters dSAParameters = (aa as DSA).ExportParameters(includePrivateParameters: false); ASN1 aSN3 = new ASN1(48); aSN3.Add(ASN1Convert.FromUnsignedBigInteger(dSAParameters.P)); aSN3.Add(ASN1Convert.FromUnsignedBigInteger(dSAParameters.Q)); aSN3.Add(ASN1Convert.FromUnsignedBigInteger(dSAParameters.G)); aSN.Add(PKCS7.AlgorithmIdentifier("1.2.840.10040.4.1", aSN3)); ASN1 aSN4 = aSN.Add(new ASN1(3)); aSN4.Add(ASN1Convert.FromUnsignedBigInteger(dSAParameters.Y)); } return(aSN); }
public static void Run() { // ExStart:HideDigitallySignedByCaption // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdfFacades_SecuritySignatures(); string inPfxFile = dataDir + "SampleCertificate.pfx"; string inFile = dataDir + "input.pdf"; string outFile = dataDir + "output.pdf"; using (PdfFileSignature pdfSign = new PdfFileSignature()) { pdfSign.BindPdf(inFile); //create a rectangle for signature location System.Drawing.Rectangle rect = new System.Drawing.Rectangle(310, 45, 200, 50); //create any of the three signature types PKCS7 pkcs = new PKCS7(inPfxFile, "idsrv3test"); SignatureCustomAppearance signatureCustomAppearance = new SignatureCustomAppearance(); signatureCustomAppearance.FontSize = 6; signatureCustomAppearance.FontFamilyName = "Times New Roman"; signatureCustomAppearance.DigitalSignedLabel = "Signed by me"; pkcs.CustomAppearance = signatureCustomAppearance; // sign the PDF file pdfSign.Sign(1, true, rect, pkcs); //save output PDF file pdfSign.Save(outFile); } // ExEnd:HideDigitallySignedByCaption }
/// /// SEQUENCE (a) /// +- INTEGER (V) // Version - 0 (v1998) /// +- SEQUENCE (b) /// | +- OID (oid) // 1.2.840.113549.1.1.1 /// | +- Nil (c) /// +- OCTETSTRING(PRVKY) (os) // Private Key Parameter /// /// However, OCTETSTRING(PRVKY) wraps /// SEQUENCE( /// INTEGER(0) // Version - 0 (v1998) /// INTEGER(N) /// INTEGER(E) /// INTEGER(D) /// INTEGER(P) /// INTEGER(Q) /// INTEGER(DP) /// INTEGER(DQ) /// INTEGER(InvQ) /// ) public static byte[] RSAKeyToASN1(RSAParameters PrivateKey) { ASN1 v = ASN1Convert.FromUnsignedBigInteger(new byte[] { 0 }); ASN1 b = PKCS7.AlgorithmIdentifier("1.2.840.113549.1.1.1"); ASN1 os = new ASN1(0x30); os.Add(ASN1Convert.FromUnsignedBigInteger(new byte[] { 0 })); os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.Modulus)); os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.Exponent)); os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.D)); os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.P)); os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.Q)); os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.DP)); os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.DQ)); os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.InverseQ)); ASN1 pem = new ASN1(0x30); pem.Add(v); pem.Add(b); // Make this into an OCTET string pem.Add(new ASN1(0x04, os.GetBytes())); return(pem.GetBytes()); }
private ASN1 SubjectPublicKeyInfo() { ASN1 asn = new ASN1(48); if (this.aa is RSA) { asn.Add(PKCS7.AlgorithmIdentifier("1.2.840.113549.1.1.1")); RSAParameters rsaparameters = (this.aa as RSA).ExportParameters(false); ASN1 asn2 = new ASN1(48); asn2.Add(ASN1Convert.FromUnsignedBigInteger(rsaparameters.Modulus)); asn2.Add(ASN1Convert.FromUnsignedBigInteger(rsaparameters.Exponent)); asn.Add(new ASN1(this.UniqueIdentifier(asn2.GetBytes()))); } else { if (!(this.aa is DSA)) { throw new NotSupportedException("Unknown Asymmetric Algorithm " + this.aa.ToString()); } DSAParameters dsaparameters = (this.aa as DSA).ExportParameters(false); ASN1 asn3 = new ASN1(48); asn3.Add(ASN1Convert.FromUnsignedBigInteger(dsaparameters.P)); asn3.Add(ASN1Convert.FromUnsignedBigInteger(dsaparameters.Q)); asn3.Add(ASN1Convert.FromUnsignedBigInteger(dsaparameters.G)); asn.Add(PKCS7.AlgorithmIdentifier("1.2.840.10040.4.1", asn3)); ASN1 asn4 = asn.Add(new ASN1(3)); asn4.Add(ASN1Convert.FromUnsignedBigInteger(dsaparameters.Y)); } return(asn); }
protected override ASN1 ToBeSigned(string oid) { // TBSCertificate ASN1 tbsCert = new ASN1(0x30); if (version > 1) { // TBSCertificate / [0] Version DEFAULT v1, byte[] ver = { (byte)(version - 1) }; ASN1 v = tbsCert.Add(new ASN1(0xA0)); v.Add(new ASN1(0x02, ver)); } // TBSCertificate / CertificateSerialNumber, tbsCert.Add(new ASN1(0x02, sn)); // TBSCertificate / AlgorithmIdentifier, tbsCert.Add(PKCS7.AlgorithmIdentifier(oid)); // TBSCertificate / Name tbsCert.Add(X501.FromString(issuer)); // TBSCertificate / Validity ASN1 validity = tbsCert.Add(new ASN1(0x30)); // TBSCertificate / Validity / Time validity.Add(ASN1Convert.FromDateTime(notBefore)); // TBSCertificate / Validity / Time validity.Add(ASN1Convert.FromDateTime(notAfter)); // TBSCertificate / Name tbsCert.Add(X501.FromString(subject)); // TBSCertificate / SubjectPublicKeyInfo tbsCert.Add(SubjectPublicKeyInfo()); if (version > 1) { // TBSCertificate / [1] IMPLICIT UniqueIdentifier OPTIONAL if (issuerUniqueID != null) { tbsCert.Add(new ASN1(0xA1, UniqueIdentifier(issuerUniqueID))); } // TBSCertificate / [2] IMPLICIT UniqueIdentifier OPTIONAL if (subjectUniqueID != null) { tbsCert.Add(new ASN1(0xA1, UniqueIdentifier(subjectUniqueID))); } // TBSCertificate / [3] Extensions OPTIONAL if ((version > 2) && (extensions.Count > 0)) { tbsCert.Add(new ASN1(0xA3, extensions.GetBytes())); } } return(tbsCert); }
private static void Run_34561_tests() { // ExStart:Run_34561_tests new License().SetLicense(@"E:\Aspose.Pdf.lic"); string inSingleSignedFile = @"C:\pdftest\PDFNEWNET_34561_SingleSigned.pdf"; string outSingleUnsignedFile = @"C:\pdftest\PDFNEWNET_34561_SingleUnSigned.pdf"; string inOutSingleResignedFile = @"C:\pdftest\PDFNEWNET_34561_SingleReSigned.pdf"; PdfFileSignature pdfSignSingle = new PdfFileSignature(); pdfSignSingle.BindPdf(inSingleSignedFile); IList names = pdfSignSingle.GetSignNames(); Stream pfx = new FileStream(@"C:\pdftest\test1.pfx", FileMode.Open); PKCS7 pcks = new PKCS7(pfx, "test1"); string sigNameSingle = names[0] as string; if (sigNameSingle != null && sigNameSingle != string.Empty) { pdfSignSingle.RemoveSignature(sigNameSingle, false); pdfSignSingle.Save(outSingleUnsignedFile); PdfFileSignature pdfSignSingle2 = new PdfFileSignature(); pdfSignSingle2.BindPdf(outSingleUnsignedFile); pdfSignSingle2.SignatureAppearance = @"C:\pdftest\butterfly.jpg"; pdfSignSingle2.Sign("Signature1", pcks); pdfSignSingle2.Save(inOutSingleResignedFile); pdfSignSingle2.BindPdf(inOutSingleResignedFile); // Assert.True(pdfSignSingle2.VerifySignature("Signature1")); Console.Write("Signature 1 check result : " + pdfSignSingle2.VerifySignature("Signature1").ToString() + " \n"); } // Test file with multiple signatures string outManyUnsignedFile = @"C:\pdftest\PDFNEWNET_34561_ManyUnSigned.pdf"; string inOutManyResignedFile = @"C:\pdftest\PDFNEWNET_34561_ManyReSigned.pdf"; PdfFileSignature pdfSignMany = new Aspose.Pdf.Facades.PdfFileSignature(); IList sigNames = pdfSignMany.GetSignNames(); foreach (string sigName in sigNames) { pdfSignMany.RemoveSignature(sigName, false); } pdfSignMany.Save(outManyUnsignedFile); PdfFileSignature pdfSignMany2 = new PdfFileSignature(); pdfSignMany2.BindPdf(outManyUnsignedFile); pdfSignMany2.Sign("Signature1", pcks); pdfSignMany2.Save(inOutManyResignedFile); pdfSignMany2.BindPdf(inOutSingleResignedFile); // Assert.IsTrue(pdfSignMany2.VerifySignature("Signature1")); Console.Write("Signature 2 check result : " + pdfSignMany2.VerifySignature("Signature1").ToString() + " "); // ExEnd:Run_34561_tests }
private byte[] Build(ASN1 tbs, string hashoid, byte[] signature) { ASN1 asn = new ASN1(48); asn.Add(tbs); asn.Add(PKCS7.AlgorithmIdentifier(hashoid)); byte[] array = new byte[signature.Length + 1]; Buffer.BlockCopy(signature, 0, array, 1, signature.Length); asn.Add(new ASN1(3, array)); return(asn.GetBytes()); }
public static void Run() { try { // ExStart:DigitallySign // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures(); string pbxFile = ""; string inFile = dataDir + @"DigitallySign.pdf"; string outFile = dataDir + @"DigitallySign_out_.pdf"; using (Document document = new Document(inFile)) { using (PdfFileSignature signature = new PdfFileSignature(document)) { PKCS7 pkcs = new PKCS7(pbxFile, "WebSales"); // Use PKCS7/PKCS7Detached objects DocMDPSignature docMdpSignature = new DocMDPSignature(pkcs, DocMDPAccessPermissions.FillingInForms); System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100, 100, 200, 100); // Set signature appearance signature.SignatureAppearance = dataDir + @"aspose-logo.jpg"; // Create any of the three signature types signature.Certify(1, "Signature Reason", "Contact", "Location", true, rect, docMdpSignature); // Save output PDF file signature.Save(outFile); } } using (Document document = new Document(outFile)) { using (PdfFileSignature signature = new PdfFileSignature(document)) { IList sigNames = signature.GetSignNames(); if (sigNames.Count > 0) // Any signatures? { if (signature.VerifySigned(sigNames[0] as string)) // Verify first one { if (signature.IsCertified) // Certified? { if (signature.GetAccessPermissions() == DocMDPAccessPermissions.FillingInForms) // Get access permission { // Do something } } } } } } // ExEnd:DigitallySign } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private byte[] Build(ASN1 tbs, string hashoid, byte[] signature) { ASN1 builder = new ASN1(0x30); builder.Add(tbs); builder.Add(PKCS7.AlgorithmIdentifier(hashoid)); // first byte of BITSTRING is the number of unused bits in the first byte byte[] bitstring = new byte [signature.Length + 1]; Buffer.BlockCopy(signature, 0, bitstring, 1, signature.Length); builder.Add(new ASN1(0x03, bitstring)); return(builder.GetBytes()); }
public static void Run() { try { // ExStart:DigitallySign // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures(); string pbxFile = ""; string inFile = dataDir + @"DigitallySign.pdf"; string outFile = dataDir + @"DigitallySign_out.pdf"; using (Document document = new Document(inFile)) { using (PdfFileSignature signature = new PdfFileSignature(document)) { PKCS7 pkcs = new PKCS7(pbxFile, "WebSales"); // Use PKCS7/PKCS7Detached objects DocMDPSignature docMdpSignature = new DocMDPSignature(pkcs, DocMDPAccessPermissions.FillingInForms); System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100, 100, 200, 100); // Set signature appearance signature.SignatureAppearance = dataDir + @"aspose-logo.jpg"; // Create any of the three signature types signature.Certify(1, "Signature Reason", "Contact", "Location", true, rect, docMdpSignature); // Save output PDF file signature.Save(outFile); } } using (Document document = new Document(outFile)) { using (PdfFileSignature signature = new PdfFileSignature(document)) { IList sigNames = signature.GetSignNames(); if (sigNames.Count > 0) // Any signatures? { if (signature.VerifySigned(sigNames[0] as string)) // Verify first one { if (signature.IsCertified) // Certified? { if (signature.GetAccessPermissions() == DocMDPAccessPermissions.FillingInForms) // Get access permission { // Do something } } } } } } // ExEnd:DigitallySign } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); string inFile = dataDir + @"input.pdf"; string outFile = dataDir + @"output.pdf"; using (Document document = new Document(inFile)) { using (PdfFileSignature signature = new PdfFileSignature(document)) { PKCS7 pkcs = new PKCS7(@"c:\test.pfx", "WebSales"); // Use PKCS7/PKCS7Detached objects DocMDPSignature docMdpSignature = new DocMDPSignature(pkcs, DocMDPAccessPermissions.FillingInForms); System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100, 100, 200, 100); //set signature appearance signature.SignatureAppearance = dataDir + @"aspose-logo.jpg"; //create any of the three signature types signature.Certify(1, "Signature Reason", "Contact", "Location", true, rect, docMdpSignature); //save output PDF file signature.Save(outFile); } } using (Document document = new Document(outFile)) { using (PdfFileSignature signature = new PdfFileSignature(document)) { IList sigNames = signature.GetSignNames(); if (sigNames.Count > 0) // Any signatures? { if (signature.VerifySigned(sigNames[0] as string)) // Verify first one { if (signature.IsCertified) // Certified? { if (signature.GetAccessPermissions() == DocMDPAccessPermissions.FillingInForms) // Get access permission { // Do something } } } } } } }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); string inFile = dataDir+ @"input.pdf"; string outFile = dataDir + @"output.pdf"; using (Document document = new Document(inFile)) { using (PdfFileSignature signature = new PdfFileSignature(document)) { PKCS7 pkcs = new PKCS7(@"c:\test.pfx", "WebSales"); // Use PKCS7/PKCS7Detached objects DocMDPSignature docMdpSignature = new DocMDPSignature(pkcs, DocMDPAccessPermissions.FillingInForms); System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100, 100, 200, 100); //set signature appearance signature.SignatureAppearance = dataDir + @"aspose-logo.jpg"; //create any of the three signature types signature.Certify(1, "Signature Reason", "Contact", "Location", true, rect, docMdpSignature); //save output PDF file signature.Save(outFile); } } using (Document document = new Document(outFile)) { using (PdfFileSignature signature = new PdfFileSignature(document)) { IList sigNames = signature.GetSignNames(); if (sigNames.Count > 0) // Any signatures? { if (signature.VerifySigned(sigNames[0] as string)) // Verify first one { if (signature.IsCertified) // Certified? { if (signature.GetAccessPermissions() == DocMDPAccessPermissions.FillingInForms) // Get access permission { // Do something } } } } } } }
internal static void SignPdfDocument(string filename, string certificate, string password) { var path = $"original\\{filename}"; var certPath = $"certificates\\{certificate}"; var authority = "Υπουργείο Εσωτερικών"; var contactInfo = "Ιωάννου Κωνσταντίνος"; var location = "Αθήνα"; var reason = "ΑΠ: 4322/12"; using (Aspose.Pdf.Document doc = new Aspose.Pdf.Document(path)) { var signature = new Aspose.Pdf.Facades.PdfFileSignature(doc); // Create digital signature PKCS7 sig = new PKCS7(certPath, password); // Use PKCS7/PKCS7Detached objects sig.Authority = authority; sig.ContactInfo = contactInfo; sig.Location = location; sig.Reason = reason; sig.ShowProperties = false; // Set signature position var size = 50; var llx = doc.Pages[1].Rect.URX - size - 10; var lly = doc.Pages[1].Rect.URY - size - 10; var urx = doc.Pages[1].Rect.URX - 10; var ury = doc.Pages[1].Rect.URY - 10; var rect = new Aspose.Pdf.Rectangle(llx, lly, urx, ury); // Set signature background image var lines = new List <string>() { authority, reason, contactInfo, location }; signature.SignatureAppearanceStream = createSigningImage("sign_stamp.png", lines); // Sign the document signature.Sign(1, true, rect.ToRect(), sig); // Save output PDF file var outputPath = $"revised\\signed_{filename}"; signature.Save(outputPath); } Console.WriteLine("signed...."); }
/* SubjectPublicKeyInfo ::= SEQUENCE { * algorithm AlgorithmIdentifier, * subjectPublicKey BIT STRING } */ private ASN1 SubjectPublicKeyInfo() { ASN1 keyInfo = new ASN1(0x30); if (aa is RSA) { keyInfo.Add(PKCS7.AlgorithmIdentifier("1.2.840.113549.1.1.1")); RSAParameters p = (aa as RSA).ExportParameters(false); /* RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER } -- e */ ASN1 key = new ASN1(0x30); key.Add(ASN1Convert.FromUnsignedBigInteger(p.Modulus)); key.Add(ASN1Convert.FromUnsignedBigInteger(p.Exponent)); keyInfo.Add(new ASN1(UniqueIdentifier(key.GetBytes()))); } else if (aa is DSA) { DSAParameters p = (aa as DSA).ExportParameters(false); /* Dss-Parms ::= SEQUENCE { * p INTEGER, * q INTEGER, * g INTEGER } */ ASN1 param = new ASN1(0x30); param.Add(ASN1Convert.FromUnsignedBigInteger(p.P)); param.Add(ASN1Convert.FromUnsignedBigInteger(p.Q)); param.Add(ASN1Convert.FromUnsignedBigInteger(p.G)); keyInfo.Add(PKCS7.AlgorithmIdentifier("1.2.840.10040.4.1", param)); ASN1 key = keyInfo.Add(new ASN1(0x03)); // DSAPublicKey ::= INTEGER -- public key, y key.Add(ASN1Convert.FromUnsignedBigInteger(p.Y)); } else { throw new NotSupportedException("Unknown Asymmetric Algorithm " + aa.ToString()); } return(keyInfo); }
public void Unsorted() { ASN1 dt = ASN1Convert.FromDateTime(DateTime.UtcNow); ASN1 st = PKCS7.Attribute(PKCS7.Oid.signingTime, dt); PKCS7.SignedData sd = new PKCS7.SignedData(); sd.ContentInfo.ContentType = PKCS7.Oid.data; sd.ContentInfo.Content.Add(new ASN1(0x04, Encoding.UTF8.GetBytes("Mono"))); sd.SignerInfo.AuthenticatedAttributes.Add(st); sd.SignerInfo.Key = key; // note: key and cert and unrelated - this is just for testing sd.SignerInfo.Certificate = new X509Certificate(cert); sd.HashName = "SHA1"; // this trigger the addition of two new AA byte[] result = sd.GetBytes(); Assert.AreEqual(3, sd.SignerInfo.AuthenticatedAttributes.Count, "aa-Count"); // verify that attributes are sorted (as they are stored in a SET) Assert.AreEqual(24, (sd.SignerInfo.AuthenticatedAttributes [0] as ASN1).Length, "0"); Assert.AreEqual(28, (sd.SignerInfo.AuthenticatedAttributes [1] as ASN1).Length, "1"); Assert.AreEqual(35, (sd.SignerInfo.AuthenticatedAttributes [2] as ASN1).Length, "2"); }
protected override ASN1 ToBeSigned(string oid) { ASN1 aSN = new ASN1(48); if (version > 1) { byte[] data = new byte[1] { (byte)(version - 1) }; ASN1 aSN2 = aSN.Add(new ASN1(160)); aSN2.Add(new ASN1(2, data)); } aSN.Add(new ASN1(2, sn)); aSN.Add(PKCS7.AlgorithmIdentifier(oid)); aSN.Add(X501.FromString(issuer)); ASN1 aSN3 = aSN.Add(new ASN1(48)); aSN3.Add(ASN1Convert.FromDateTime(notBefore)); aSN3.Add(ASN1Convert.FromDateTime(notAfter)); aSN.Add(X501.FromString(subject)); aSN.Add(SubjectPublicKeyInfo()); if (version > 1) { if (issuerUniqueID != null) { aSN.Add(new ASN1(161, UniqueIdentifier(issuerUniqueID))); } if (subjectUniqueID != null) { aSN.Add(new ASN1(161, UniqueIdentifier(subjectUniqueID))); } if (version > 2 && extensions.Count > 0) { aSN.Add(new ASN1(163, extensions.GetBytes())); } } return(aSN); }
protected override ASN1 ToBeSigned(string oid) { ASN1 asn = new ASN1(48); if (this.version > 1) { byte[] data = new byte[] { this.version - 1 }; ASN1 asn2 = asn.Add(new ASN1(160)); asn2.Add(new ASN1(2, data)); } asn.Add(new ASN1(2, this.sn)); asn.Add(PKCS7.AlgorithmIdentifier(oid)); asn.Add(X501.FromString(this.issuer)); ASN1 asn3 = asn.Add(new ASN1(48)); asn3.Add(ASN1Convert.FromDateTime(this.notBefore)); asn3.Add(ASN1Convert.FromDateTime(this.notAfter)); asn.Add(X501.FromString(this.subject)); asn.Add(this.SubjectPublicKeyInfo()); if (this.version > 1) { if (this.issuerUniqueID != null) { asn.Add(new ASN1(161, this.UniqueIdentifier(this.issuerUniqueID))); } if (this.subjectUniqueID != null) { asn.Add(new ASN1(161, this.UniqueIdentifier(this.subjectUniqueID))); } if (this.version > 2 && this.extensions.Count > 0) { asn.Add(new ASN1(163, this.extensions.GetBytes())); } } return(asn); }
public static void Run() { // ExStart:DigitallySignWithTimeStamp // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures(); string pfxFile = ""; using (Document document = new Document(dataDir + @"DigitallySign.pdf")) { using (PdfFileSignature signature = new PdfFileSignature(document)) { PKCS7 pkcs = new PKCS7(pfxFile, "pfx_password"); TimestampSettings timestampSettings = new TimestampSettings("https:\\your_timestamp_settings", "user:password"); // User/Password can be omitted pkcs.TimestampSettings = timestampSettings; System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100, 100, 200, 100); // Create any of the three signature types signature.Sign(1, "Signature Reason", "Contact", "Location", true, rect, pkcs); // Save output PDF file signature.Save(dataDir + "DigitallySignWithTimeStamp_out.pdf"); } } // ExEnd:DigitallySignWithTimeStamp }
protected override ASN1 ToBeSigned(string oid) { ASN1 asN1_1 = new ASN1((byte)48); if (this.version > (byte)1) { byte[] data = new byte[1] { (byte)((uint)this.version - 1U) }; asN1_1.Add(new ASN1((byte)160)).Add(new ASN1((byte)2, data)); } asN1_1.Add(new ASN1((byte)2, this.sn)); asN1_1.Add(PKCS7.AlgorithmIdentifier(oid)); asN1_1.Add(X501.FromString(this.issuer)); ASN1 asN1_2 = asN1_1.Add(new ASN1((byte)48)); asN1_2.Add(ASN1Convert.FromDateTime(this.notBefore)); asN1_2.Add(ASN1Convert.FromDateTime(this.notAfter)); asN1_1.Add(X501.FromString(this.subject)); asN1_1.Add(this.SubjectPublicKeyInfo()); if (this.version > (byte)1) { if (this.issuerUniqueID != null) { asN1_1.Add(new ASN1((byte)161, this.UniqueIdentifier(this.issuerUniqueID))); } if (this.subjectUniqueID != null) { asN1_1.Add(new ASN1((byte)161, this.UniqueIdentifier(this.subjectUniqueID))); } if (this.version > (byte)2 && this.extensions.Count > 0) { asN1_1.Add(new ASN1((byte)163, this.extensions.GetBytes())); } } return(asN1_1); }
public static void Run() { // ExStart:DigitallySignWithTimeStamp // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures(); string pfxFile = ""; using (Document document = new Document(dataDir + @"DigitallySign.pdf")) { using (PdfFileSignature signature = new PdfFileSignature(document)) { PKCS7 pkcs = new PKCS7(pfxFile, "pfx_password"); TimestampSettings timestampSettings = new TimestampSettings("https:\\your_timestamp_settings", "user:password"); // User/Password can be omitted pkcs.TimestampSettings = timestampSettings; System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100, 100, 200, 100); // Create any of the three signature types signature.Sign(1, "Signature Reason", "Contact", "Location", true, rect, pkcs); // Save output PDF file signature.Save(dataDir + "DigitallySignWithTimeStamp_out_.pdf"); } } // ExEnd:DigitallySignWithTimeStamp }
private byte[] DecryptRDX(byte[] Key, byte[] Vector, byte[] Data, PaddingModes Padding = PaddingModes.Zeros) { int blockSize = Vector.Length; int dataLen = Data.Length; int blocks = Data.Length / blockSize; int lastBlock = dataLen - blockSize == 0 ? blockSize : dataLen - blockSize; byte[] outputData = new byte[Data.Length]; IPadding pad; if (Padding == PaddingModes.PKCS7) pad = new PKCS7(); else if (Padding == PaddingModes.X923) pad = new X923(); else pad = new ZeroPad(); using (ICipherMode mode = new CBC(new RDX())) { mode.Cipher.BlockSize = blockSize; mode.Init(false, Key, Vector); for (int i = 0; i < dataLen; i += blockSize) mode.Transform(Data, i, outputData, i); int size = pad.GetPaddingLength(outputData); if (size > 0) Array.Resize<byte>(ref outputData, dataLen - (size - 1)); } return outputData; }
private byte[] EncryptRDX(byte[] Key, byte[] Vector, byte[] Data, PaddingModes Padding = PaddingModes.Zeros) { int blockSize = Vector.Length; int dataLen = Data.Length; int remainder = dataLen % blockSize; int blocks = Data.Length / blockSize; int alignedSize = blocks * blockSize; int lastBlock = alignedSize - blockSize == 0 ? blockSize : alignedSize - blockSize; int outSize = remainder > 0 ? alignedSize + blockSize : alignedSize; byte[] outputData = new byte[outSize]; IPadding pad; if (Padding == PaddingModes.PKCS7) pad = new PKCS7(); else if (Padding == PaddingModes.X923) pad = new X923(); else pad = new ZeroPad(); using (ICipherMode mode = new CBC(new RDX())) { mode.Cipher.BlockSize = blockSize; mode.Init(true, Key, Vector); for (int i = 0; i < alignedSize; i += blockSize) mode.Transform(Data, i, outputData, i); if (remainder > 0) { byte[] temp = new byte[blockSize]; Buffer.BlockCopy(Data, alignedSize, temp, 0, remainder); pad.AddPadding(temp, (int)remainder); mode.Transform(temp, 0, outputData, blockSize); } } return outputData; }
private bool VerifyCounterSignature (PKCS7.SignerInfo cs, byte[] signature) { // SEQUENCE { // INTEGER 1 if (cs.Version != 1) return false; // SEQUENCE { // SEQUENCE { string contentType = null; ASN1 messageDigest = null; for (int i=0; i < cs.AuthenticatedAttributes.Count; i++) { // SEQUENCE { // OBJECT IDENTIFIER ASN1 attr = (ASN1) cs.AuthenticatedAttributes [i]; string oid = ASN1Convert.ToOid (attr[0]); switch (oid) { case "1.2.840.113549.1.9.3": // contentType contentType = ASN1Convert.ToOid (attr[1][0]); break; case "1.2.840.113549.1.9.4": // messageDigest messageDigest = attr[1][0]; break; case "1.2.840.113549.1.9.5": // SEQUENCE { // OBJECT IDENTIFIER // signingTime (1 2 840 113549 1 9 5) // SET { // UTCTime '030124013651Z' // } // } timestamp = ASN1Convert.ToDateTime (attr[1][0]); break; default: break; } } if (contentType != PKCS7.Oid.data) return false; // verify message digest if (messageDigest == null) return false; // TODO: must be read from the ASN.1 structure string hashName = null; switch (messageDigest.Length) { case 16: hashName = "MD5"; break; case 20: hashName = "SHA1"; break; } HashAlgorithm ha = HashAlgorithm.Create (hashName); if (!messageDigest.CompareValue (ha.ComputeHash (signature))) return false; // verify signature byte[] counterSignature = cs.Signature; // change to SET OF (not [0]) as per PKCS #7 1.5 ASN1 aa = new ASN1 (0x31); foreach (ASN1 a in cs.AuthenticatedAttributes) aa.Add (a); byte[] p7hash = ha.ComputeHash (aa.GetBytes ()); // we need to try all certificates string issuer = cs.IssuerName; byte[] serial = cs.SerialNumber; foreach (X509Certificate x509 in coll) { if (CompareIssuerSerial (issuer, serial, x509)) { if (x509.PublicKey.Length > counterSignature.Length) { RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) x509.RSA; // we need to HACK around bad (PKCS#1 1.5) signatures made by Verisign Timestamp Service // and this means copying stuff into our own RSAManaged to get the required flexibility RSAManaged rsam = new RSAManaged (); rsam.ImportParameters (rsa.ExportParameters (false)); if (PKCS1.Verify_v15 (rsam, ha, p7hash, counterSignature, true)) { timestampChain.LoadCertificates (coll); return (timestampChain.Build (x509)); } } } } // no certificate can verify this signature! return false; }
//private bool VerifySignature (ASN1 cs, byte[] calculatedMessageDigest, string hashName) private bool VerifySignature (PKCS7.SignedData sd, byte[] calculatedMessageDigest, HashAlgorithm ha) { string contentType = null; ASN1 messageDigest = null; // string spcStatementType = null; // string spcSpOpusInfo = null; for (int i=0; i < sd.SignerInfo.AuthenticatedAttributes.Count; i++) { ASN1 attr = (ASN1) sd.SignerInfo.AuthenticatedAttributes [i]; string oid = ASN1Convert.ToOid (attr[0]); switch (oid) { case "1.2.840.113549.1.9.3": // contentType contentType = ASN1Convert.ToOid (attr[1][0]); break; case "1.2.840.113549.1.9.4": // messageDigest messageDigest = attr[1][0]; break; case "1.3.6.1.4.1.311.2.1.11": // spcStatementType (Microsoft code signing) // possible values // - individualCodeSigning (1 3 6 1 4 1 311 2 1 21) // - commercialCodeSigning (1 3 6 1 4 1 311 2 1 22) // spcStatementType = ASN1Convert.ToOid (attr[1][0][0]); break; case "1.3.6.1.4.1.311.2.1.12": // spcSpOpusInfo (Microsoft code signing) /* try { spcSpOpusInfo = System.Text.Encoding.UTF8.GetString (attr[1][0][0][0].Value); } catch (NullReferenceException) { spcSpOpusInfo = null; }*/ break; default: break; } } if (contentType != spcIndirectDataContext) return false; // verify message digest if (messageDigest == null) return false; if (!messageDigest.CompareValue (calculatedMessageDigest)) return false; // verify signature string hashOID = CryptoConfig.MapNameToOID (ha.ToString ()); // change to SET OF (not [0]) as per PKCS #7 1.5 ASN1 aa = new ASN1 (0x31); foreach (ASN1 a in sd.SignerInfo.AuthenticatedAttributes) aa.Add (a); ha.Initialize (); byte[] p7hash = ha.ComputeHash (aa.GetBytes ()); byte[] signature = sd.SignerInfo.Signature; // we need to find the specified certificate string issuer = sd.SignerInfo.IssuerName; byte[] serial = sd.SignerInfo.SerialNumber; foreach (X509Certificate x509 in coll) { if (CompareIssuerSerial (issuer, serial, x509)) { // don't verify is key size don't match if (x509.PublicKey.Length > (signature.Length >> 3)) { // return the signing certificate even if the signature isn't correct // (required behaviour for 2.0 support) signingCertificate = x509; RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) x509.RSA; if (rsa.VerifyHash (p7hash, hashOID, signature)) { signerChain.LoadCertificates (coll); trustedRoot = signerChain.Build (x509); break; } } } } // timestamp signature is optional if (sd.SignerInfo.UnauthenticatedAttributes.Count == 0) { trustedTimestampRoot = true; } else { for (int i = 0; i < sd.SignerInfo.UnauthenticatedAttributes.Count; i++) { ASN1 attr = (ASN1) sd.SignerInfo.UnauthenticatedAttributes[i]; string oid = ASN1Convert.ToOid (attr[0]); switch (oid) { case PKCS7.Oid.countersignature: // SEQUENCE { // OBJECT IDENTIFIER // countersignature (1 2 840 113549 1 9 6) // SET { PKCS7.SignerInfo cs = new PKCS7.SignerInfo (attr[1]); trustedTimestampRoot = VerifyCounterSignature (cs, signature); break; default: // we don't support other unauthenticated attributes break; } } } return (trustedRoot && trustedTimestampRoot); }
public ASN1 TimestampRequest(byte[] signature) { PKCS7.ContentInfo contentInfo = new PKCS7.ContentInfo("1.2.840.113549.1.7.1"); contentInfo.Content.Add(new ASN1(4, signature)); return(PKCS7.AlgorithmIdentifier("1.3.6.1.4.1.311.3.2.1", contentInfo.ASN1)); }
private bool VerifyCounterSignature (PKCS7.SignerInfo cs, byte[] signature) { // SEQUENCE { // INTEGER 1 if (cs.Version != 1) return false; // SEQUENCE { // SEQUENCE { string contentType = null; ASN1 messageDigest = null; for (int i=0; i < cs.AuthenticatedAttributes.Count; i++) { // SEQUENCE { // OBJECT IDENTIFIER ASN1 attr = (ASN1) cs.AuthenticatedAttributes [i]; string oid = ASN1Convert.ToOid (attr[0]); switch (oid) { case "1.2.840.113549.1.9.3": // contentType contentType = ASN1Convert.ToOid (attr[1][0]); break; case "1.2.840.113549.1.9.4": // messageDigest messageDigest = attr[1][0]; break; case "1.2.840.113549.1.9.5": // SEQUENCE { // OBJECT IDENTIFIER // signingTime (1 2 840 113549 1 9 5) // SET { // UTCTime '030124013651Z' // } // } timestamp = ASN1Convert.ToDateTime (attr[1][0]); break; default: break; } } if (contentType != PKCS7.Oid.data) return false; // verify message digest if (messageDigest == null) return false; // TODO: must be read from the ASN.1 structure string hashName = null; switch (messageDigest.Length) { case 16: hashName = "MD5"; break; case 20: hashName = "SHA1"; break; } HashAlgorithm ha = HashAlgorithm.Create (hashName); if (!messageDigest.CompareValue (ha.ComputeHash (signature))) return false; // verify signature byte[] counterSignature = cs.Signature; string hashOID = CryptoConfig.MapNameToOID (hashName); // change to SET OF (not [0]) as per PKCS #7 1.5 ASN1 aa = new ASN1 (0x31); foreach (ASN1 a in cs.AuthenticatedAttributes) aa.Add (a); byte[] p7hash = ha.ComputeHash (aa.GetBytes ()); // we need to try all certificates string issuer = cs.IssuerName; byte[] serial = cs.SerialNumber; foreach (X509Certificate x509 in coll) { if (CompareIssuerSerial (issuer, serial, x509)) { // don't verify if key size don't match if (x509.PublicKey.Length > (counterSignature.Length >> 3)) { RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) x509.RSA; if (rsa.VerifyHash (p7hash, hashOID, counterSignature)) { timestampChain.LoadCertificates (coll); return (timestampChain.Build (x509)); } } } } // no certificate can verify this signature! return false; }
/// <summary> /// Computes and shows the crypto results. /// </summary> private void TestAllAlgorithms() { /** * Input length is 17 chars but 19 bytes. */ String input = "Hello to € World!"; /** * Arrays for padding testing. */ Byte[] pb = new Byte[12] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; Byte[] nb = new Byte[12] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; /** * Test PKCS#7 padding. */ Byte[] pp = PKCS7.Pad(pb, 8); Byte[] pu = PKCS7.Unpad(pp); // this.outputBox.Text += "PKCS#7 padded: " + BytesToString(pp) + "\n"; this.outputBox.Text += "PKCS#7 unpadded: " + BytesToString(pu) + "\n"; this.outputBox.Text += "\n"; /** * Test zero byte padding. */ Byte[] np = ZEROS.Pad(nb, 8); Byte[] nu = ZEROS.Unpad(np); // this.outputBox.Text += "Zero byte padded: " + BytesToString(np) + "\n"; this.outputBox.Text += "Zero byte unpadded: " + BytesToString(nu) + "\n"; this.outputBox.Text += "\n"; /** * Text to bytes conversion from input. */ Byte[] utf8Bytes = Encoding.UTF8.GetBytes(input); Byte[] ubeBytes = Encoding.BigEndianUnicode.GetBytes(input); Byte[] uleBytes = Encoding.Unicode.GetBytes(input); // this.outputBox.Text += "UTF-16 BE bytes: " + BytesToString(ubeBytes) + "\n"; this.outputBox.Text += "UTF-16 LE bytes: " + BytesToString(uleBytes) + "\n"; this.outputBox.Text += "UTF-8 bytes: " + BytesToString(utf8Bytes) + "\n"; this.outputBox.Text += "\n"; /** * Test base16 encoding. */ String b16e = Base16.Encode(utf8Bytes); Byte[] b16d = Base16.Decode(b16e); // this.outputBox.Text += "Base16 encoded in UTF-8: " + b16e + "\n"; this.outputBox.Text += "Base16 decoded in UTF-8: " + Encoding.UTF8.GetString(b16d) + "\n"; this.outputBox.Text += "\n"; /** * Test base64 encoding. */ String b64e = Base64.Encode(utf8Bytes); Byte[] b64d = Base64.Decode(b64e); // this.outputBox.Text += "Base64 encoded in UTF-8: " + b64e + "\n"; this.outputBox.Text += "Base64 decoded in UTF-8: " + Encoding.UTF8.GetString(b64d) + "\n"; this.outputBox.Text += "\n"; /** * Test generating GUID's. */ String guid1 = GUID.Create(); String guid2 = GUID.Create(); String guid3 = GUID.Create(); // this.outputBox.Text += "Generated GUID 1: " + guid1 + "\n"; this.outputBox.Text += "Generated GUID 2: " + guid2 + "\n"; this.outputBox.Text += "Generated GUID 3: " + guid3 + "\n"; this.outputBox.Text += "\n"; /** * Test ROT13 encoding. */ Byte[] r13e = ROT13.Encode(utf8Bytes); Byte[] r13d = ROT13.Decode(r13e); // this.outputBox.Text += "ROT13 encrypted in UTF-8: " + Encoding.UTF8.GetString(r13e) + "\n"; this.outputBox.Text += "ROT13 decrypted in UTF-8: " + Encoding.UTF8.GetString(r13d) + "\n"; this.outputBox.Text += "\n"; /** * Test MD5 with one official test vector and custom input. * Vectors from: http://www.febooti.com/products/filetweak/members/hash-and-crc/test-vectors/ */ Byte[] md5tv = MD5.Compute(new Byte[0]); Byte[] md5utf8 = MD5.Compute(utf8Bytes); Byte[] md5key = Encoding.UTF8.GetBytes("1234567890123456"); Byte[] md5hmac = MD5.ComputeHMAC(md5key, utf8Bytes); // this.outputBox.Text += "MD5 from otv is ok: " + (Base16.Encode(md5tv) == "d41d8cd98f00b204e9800998ecf8427e").ToString() + "\n"; this.outputBox.Text += "MD5 HMAC in UTF-8: " + Base16.Encode(md5hmac) + "\n"; this.outputBox.Text += "MD5 in UTF-8: " + Base16.Encode(md5utf8) + "\n"; this.outputBox.Text += "\n"; /** * Test RIPEMD-160 with one official test vector and custom input. * Vectors from: http://www.febooti.com/products/filetweak/members/hash-and-crc/test-vectors/ */ Byte[] rmd160tv = RMD160.Compute(new Byte[0]); Byte[] rmd160utf8 = RMD160.Compute(utf8Bytes); Byte[] rmd160key = Encoding.UTF8.GetBytes("1234567890123456"); Byte[] rmd160hmac = RMD160.ComputeHMAC(rmd160key, utf8Bytes); // this.outputBox.Text += "RIPEMD-160 from otv is ok: " + (Base16.Encode(rmd160tv) == "9c1185a5c5e9fc54612808977ee8f548b2258d31").ToString() + "\n"; this.outputBox.Text += "RIPEMD-160 HMAC in UTF-8: " + Base16.Encode(rmd160hmac) + "\n"; this.outputBox.Text += "RIPEMD-160 in UTF-8: " + Base16.Encode(rmd160utf8) + "\n"; this.outputBox.Text += "\n"; /** * Test SHA-1 with one official test vector and custom input. * Vectors from: http://www.febooti.com/products/filetweak/members/hash-and-crc/test-vectors/ */ Byte[] sha1tv = SHA1.Compute(new Byte[0]); Byte[] sha1utf8 = SHA1.Compute(utf8Bytes); Byte[] sha1key = Encoding.UTF8.GetBytes("1234567890123456"); Byte[] sha1hmac = SHA1.ComputeHMAC(sha1key, utf8Bytes); // this.outputBox.Text += "SHA-1 from otv is ok: " + (Base16.Encode(sha1tv) == "da39a3ee5e6b4b0d3255bfef95601890afd80709").ToString() + "\n"; this.outputBox.Text += "SHA-1 HMAC in UTF-8: " + Base16.Encode(sha1hmac) + "\n"; this.outputBox.Text += "SHA-1 in UTF-8: " + Base16.Encode(sha1utf8) + "\n"; this.outputBox.Text += "\n"; /** * Test SHA-256 with one official test vector and custom input. * Vectors from: http://www.febooti.com/products/filetweak/members/hash-and-crc/test-vectors/ */ Byte[] sha256tv = SHA256.Compute(new Byte[0]); Byte[] sha256utf8 = SHA256.Compute(utf8Bytes); Byte[] sha256key = Encoding.UTF8.GetBytes("1234567890123456"); Byte[] sha256hmac = SHA256.ComputeHMAC(sha256key, utf8Bytes); // this.outputBox.Text += "SHA-256 from otv is ok: " + (Base16.Encode(sha256tv) == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855").ToString() + "\n"; this.outputBox.Text += "SHA-256 HMAC in UTF-8: " + Base16.Encode(sha256hmac) + "\n"; this.outputBox.Text += "SHA-256 in UTF-8: " + Base16.Encode(sha256utf8) + "\n"; this.outputBox.Text += "\n"; /** * Test ARC4 with one official test vector and custom input. * Vectors from: http://reikon.us/arc4 */ Byte[] arc4tvk = Base16.Decode("0123456789abcdef"); Byte[] arc4tvt = Base16.Decode("0123456789abcdef"); Byte[] arc4tve = ARC4.Encrypt(arc4tvk, arc4tvt); Byte[] arc4tvd = ARC4.Decrypt(arc4tvk, arc4tve); // Byte[] arc4k = Encoding.UTF8.GetBytes("1234567890123456"); Byte[] arc4e = ARC4.Encrypt(arc4k, utf8Bytes); Byte[] arc4d = ARC4.Decrypt(arc4k, arc4e); // this.outputBox.Text += "ARC4 otv encrypted is ok: " + (Base16.Encode(arc4tve) == "75b7878099e0c596") + "\n"; this.outputBox.Text += "ARC4 otv decrypted is ok: " + (Base16.Encode(arc4tvd) == "0123456789abcdef") + "\n"; this.outputBox.Text += "ARC4 encrypted in UTF-8: " + Base16.Encode(arc4e) + "\n"; this.outputBox.Text += "ARC4 decrypted in UTF-8: " + Encoding.UTF8.GetString(arc4d) + "\n"; this.outputBox.Text += "\n"; /** * Test XXTEA with one official test vector and custom input. * Vectors from: http://www.crypt.co.za/post/27 */ Byte[] xxttvk = Base16.Decode("9e3779b99b9773e9b979379e6b695156"); Byte[] xxttvt = Base16.Decode("0102040810204080fffefcf8f0e0c080"); Byte[] xxttve = XXTEA.Encrypt(xxttvk, xxttvt); Byte[] xxttvd = XXTEA.Decrypt(xxttvk, xxttve); // Byte[] xxteak = Encoding.UTF8.GetBytes("1234567890123456"); Byte[] xxteae = XXTEA.Encrypt(xxteak, PKCS7.Pad(utf8Bytes, 4)); Byte[] xxtead = PKCS7.Unpad(XXTEA.Decrypt(xxteak, xxteae)); // this.outputBox.Text += "XXTEA otv encrypted is ok: " + (Base16.Encode(xxttve) == "01b815fd2e4894d13555da434c9d868a") + "\n"; this.outputBox.Text += "XXTEA otv decrypted is ok: " + (Base16.Encode(xxttvd) == "0102040810204080fffefcf8f0e0c080") + "\n"; this.outputBox.Text += "XXTEA encrypted in UTF-8: " + Base16.Encode(xxteae) + "\n"; this.outputBox.Text += "XXTEA decrypted in UTF-8: " + Encoding.UTF8.GetString(xxtead) + "\n"; this.outputBox.Text += "\n"; /** * Test AES-128 with one official test vector and custom input. * Vectors from: http://www.csrc.nist.gov/publications/fips/fips197/fips-197.pdf */ Byte[] aes128tvk = new Byte[16] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; Byte[] aes128tvt = new Byte[16] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; Byte[] aes128tve = AES.Encrypt(aes128tvk, aes128tvt, OperationMode.ECB, null); // No padding needed. Byte[] aes128tvd = AES.Decrypt(aes128tvk, aes128tve, OperationMode.ECB, null); // No padding needed. // Byte[] aes128k = Encoding.UTF8.GetBytes("1234567890123456"); Byte[] aes128e = AES.Encrypt(aes128k, PKCS7.Pad(utf8Bytes, 16), OperationMode.ECB, null); Byte[] aes128d = PKCS7.Unpad(AES.Decrypt(aes128k, aes128e, OperationMode.ECB, null)); // this.outputBox.Text += "AES-128 otv encrypted is ok: " + (Base16.Encode(aes128tve) == "69c4e0d86a7b0430d8cdb78070b4c55a") + "\n"; this.outputBox.Text += "AES-128 otv decrypted is ok: " + (Base16.Encode(aes128tvd) == "00112233445566778899aabbccddeeff") + "\n"; this.outputBox.Text += "AES-128 (ECB mode) encrypted in UTF-8: " + Base16.Encode(aes128e) + "\n"; this.outputBox.Text += "AES-128 (ECB mode) decrypted in UTF-8: " + Encoding.UTF8.GetString(aes128d) + "\n"; this.outputBox.Text += "\n"; /** * Test AES-192 with one official test vector and custom input. * Vectors from: http://www.csrc.nist.gov/publications/fips/fips197/fips-197.pdf */ Byte[] aes192tvk = new Byte[24] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 }; Byte[] aes192tvt = new Byte[16] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; Byte[] aes192tve = AES.Encrypt(aes192tvk, aes192tvt, OperationMode.ECB, null); // No padding needed. Byte[] aes192tvd = AES.Decrypt(aes192tvk, aes192tve, OperationMode.ECB, null); // No padding needed. // Byte[] aes192i = Encoding.UTF8.GetBytes("1234567890123456"); Byte[] aes192k = Encoding.UTF8.GetBytes("123456789012345678901234"); Byte[] aes192e = AES.Encrypt(aes192k, PKCS7.Pad(utf8Bytes, 16), OperationMode.CBC, aes192i); Byte[] aes192d = PKCS7.Unpad(AES.Decrypt(aes192k, aes192e, OperationMode.CBC, aes192i)); // this.outputBox.Text += "AES-192 otv encrypted is ok: " + (Base16.Encode(aes192tve) == "dda97ca4864cdfe06eaf70a0ec0d7191") + "\n"; this.outputBox.Text += "AES-192 otv decrypted is ok: " + (Base16.Encode(aes192tvd) == "00112233445566778899aabbccddeeff") + "\n"; this.outputBox.Text += "AES-192 (CBC mode) encrypted in UTF-8: " + Base16.Encode(aes192e) + "\n"; this.outputBox.Text += "AES-192 (CBC mode) decrypted in UTF-8: " + Encoding.UTF8.GetString(aes192d) + "\n"; this.outputBox.Text += "\n"; /** * Test AES-256 with one official test vector and custom input. * Vectors from: http://www.csrc.nist.gov/publications/fips/fips197/fips-197.pdf */ Byte[] aes256tvk = new Byte[32] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f }; Byte[] aes256tvt = new Byte[16] { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff }; Byte[] aes256tve = AES.Encrypt(aes256tvk, aes256tvt, OperationMode.ECB, null); // No padding needed. Byte[] aes256tvd = AES.Decrypt(aes256tvk, aes256tve, OperationMode.ECB, null); // No padding needed. // Byte[] aes256i = Encoding.UTF8.GetBytes("1234567890123456"); Byte[] aes256k = Encoding.UTF8.GetBytes("12345678901234561234567890123456"); Byte[] aes256e = AES.Encrypt(aes256k, PKCS7.Pad(utf8Bytes, 16), OperationMode.CBC, aes256i); Byte[] aes256d = PKCS7.Unpad(AES.Decrypt(aes256k, aes256e, OperationMode.CBC, aes256i)); // this.outputBox.Text += "AES-256 otv encrypted is ok: " + (Base16.Encode(aes256tve) == "8ea2b7ca516745bfeafc49904b496089") + "\n"; this.outputBox.Text += "AES-256 otv decrypted is ok: " + (Base16.Encode(aes256tvd) == "00112233445566778899aabbccddeeff") + "\n"; this.outputBox.Text += "AES-256 (CBC mode) encrypted in UTF-8: " + Base16.Encode(aes256e) + "\n"; this.outputBox.Text += "AES-256 (CBC mode) decrypted in UTF-8: " + Encoding.UTF8.GetString(aes256d) + "\n"; this.outputBox.Text += "\n"; }
public void Challenge09_PKCS7() { Assert.Equal("YELLOW SUBMARINE\x04\x04\x04\x04", Encoding.UTF8.GetString(PKCS7.Pad(Encoding.UTF8.GetBytes("YELLOW SUBMARINE"), 20))); }
public byte[] Decrypt (PKCS7.EncryptedData ed) { return Decrypt (ed.EncryptionAlgorithm.ContentType, ed.EncryptionAlgorithm.Content [0].Value, ASN1Convert.ToInt32 (ed.EncryptionAlgorithm.Content [1]), ed.EncryptedContent); }