This is a mirror of official site: http://jasper-net.blogspot.com/

How to call CryptMsg API in streaming mode (C#)

| Sunday, April 11, 2010
The other day I posted an issue when signing large data with SignedCms  in .NET (at least up to version 3.5 SP1): "ASN1 value too large" error when calling SignedCms.ComputeSignature. In that post, I mentioned the following to work around the issue: "we will have to p/invoke CryptMsg API and use it in streaming mode".

Now the logical question will be, how do I do that? The following C# sample will show you how:

File form1.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography.X509Certificates;
using System.IO;

namespace LargeCMS
{
   public partial class Form1 : Form
   {
       public Form1()
       {
           InitializeComponent();

           subjectTextBox.Text = "ALEX";
           originalTextBox.Text = "my1GBfile.txt";
           encodedTextBox.Text = "encodeddata.p7s";
           decodedTextBox.Text = "decodeddata.txt";
       }

       private void encodeButton_Click(object sender, EventArgs e)
       {
           // Variables
           X509Store store = null;
           X509Certificate2 cert = null;
           FileStream inFile = null;
           FileStream outFile = null;
           CMS cms = null;

           try
           {
               // Get user cert
               store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
               store.Open(OpenFlags.MaxAllowed);
               cert = store.Certificates.Find(X509FindType.FindBySubjectName, subjectTextBox.Text, true)[0];

               // Open file with data to encode
               inFile = File.Open(originalTextBox.Text, FileMode.Open);

               // Create file for encoded data
               outFile = File.Create(encodedTextBox.Text);

               // Encode data
               cms = new CMS();
               cms.Encode(cert, inFile, outFile);

               MessageBox.Show("Sucess!!!");
           }


Read more: Decrypt my World

Posted via email from jasper22's posterous

0 comments: