473,395 Members | 1,537 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Encryption using X509Certificate

Hi All,

I have a *.cer file, a public key of some one and I want to encrypt some
thing using this public key.

Can someone point me to a sample code for Encrypting some file using
X509Certificate ( *.cer file ) so that it can be used to email as
attachment.

The real part is Encrypting using X509Certificate and CryptoServiceProvider.

Am I one the right track ?

Any help is appreciated.

Thanx in advance

rawCoder
Nov 17 '05 #1
2 8094
Incase someone else is also interested i found the following code snippet
useful from some newsgroup post.

// Usage
string certFile = @"c:\mycert.cer";
X509Certificate cert = X509Certificate.CreateFromCert*File(certFile);
RSACryptoServiceProvider rsa = CertUtil.GetCertPublicKey(cert*);
Console.WriteLine(rsa.ToXmlStr*ing(false));

/// CertUtil helper Class.
using System;
using System.Security.Cryptography;
using System.Runtime.InteropServices*;
using System.Security.Cryptography.X*509Certificates;
namespace WSESimpleTCPDLL
{
[StructLayout(LayoutKind.Seque*ntial)]
public struct PUBKEYBLOBHEADERS
{
public byte bType; //BLOBHEADER
public byte bVersion; //BLOBHEADER
public short reserved; //BLOBHEADER
public uint aiKeyAlg; //BLOBHEADER
public uint magic; //RSAPUBKEY
public uint bitlen; //RSAPUBKEY
public uint pubexp; //RSAPUBKEY
}
/// <summary>
/// Summary description for CertUtil.
/// </summary>
public sealed class CertUtil
{
const uint CERT_SYSTEM_STORE_CURRENT_USER = 0x00010000;
const uint CERT_STORE_READONLY_FLAG = 0x00008000;
const uint CERT_STORE_OPEN_EXISTING_FLAG = 0x00004000;
const uint CERT_FIND_SUBJECT_STR = 0x00080007;
const uint X509_ASN_ENCODING = 0x00000001;
const uint PKCS_7_ASN_ENCODING = 0x00010000;
const uint RSA_CSP_PUBLICKEYBLOB = 19;
const int AT_KEYEXCHANGE = 1; //keyspec values
const int AT_SIGNATURE = 2;
static uint ENCODING_TYPE = PKCS_7_ASN_ENCODING | X509_ASN_ENCODING ;
private CertUtil()
{
}
public static RSACryptoServiceProvider GetCertPublicKey(X509Certifica*te
cert)
{
byte[] publickeyblob ;
byte[] encodedpubkey = cert.GetPublicKey(); //asn.1 encoded public key
uint blobbytes = 0;
if(Win32.CryptDecodeObject(ENC*ODING_TYPE, RSA_CSP_PUBLICKEYBLOB,
encodedpubkey, (uint)encodedpubkey.Length, 0, null, ref blobbytes))
{
publickeyblob = new byte[blobbytes];
Win32.CryptDecodeObject(ENCODI*NG_TYPE, RSA_CSP_PUBLICKEYBLOB,
encodedpubkey, (uint)encodedpubkey.Length, 0, publickeyblob, ref blobbytes);
}
else
{
throw new Exception("Could not decode publickeyblob from certificate
publickey") ;
}
PUBKEYBLOBHEADERS pkheaders = new PUBKEYBLOBHEADERS() ;
int headerslength = Marshal.SizeOf(pkheaders);
IntPtr buffer = Marshal.AllocHGlobal( headerslength);
Marshal.Copy( publickeyblob, 0, buffer, headerslength );
pkheaders = (PUBKEYBLOBHEADERS) Marshal.PtrToStructure( buffer,
typeof(PUBKEYBLOBHEADERS) );
Marshal.FreeHGlobal( buffer );
//----- Get public exponent -------------
byte[] exponent = BitConverter.GetBytes(pkheader*s.pubexp);
//little-endian ordered
Array.Reverse(exponent); //convert to big-endian order
//----- Get modulus -------------
int modulusbytes = (int)pkheaders.bitlen/8 ;
byte[] modulus = new byte[modulusbytes];
try
{
Array.Copy(publickeyblob, headerslength, modulus, 0, modulusbytes);
Array.Reverse(modulus); //convert from little to big-endian ordering.
}
catch(Exception)
{
throw new Exception("Problem getting modulus from publickeyblob");
}
RSAParameters parms = new RSAParameters();
parms.Modulus = modulus;
parms.Exponent = exponent;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(parms);
return rsa;
}
}

}
//// Win32 Helpers
using System;
using System.Runtime.InteropServices*;
using System.ComponentModel;
using System.Collections;
using System.Text;

namespace WSESimpleTCPDLL
{
public class Win32
{
[DllImport("crypt32.dll")]
public static extern bool CryptDecodeObject(
uint CertEncodingType,
uint lpszStructType,
byte[] pbEncoded,
uint cbEncoded,
uint flags,
[In, Out] byte[] pvStructInfo,
ref uint cbStructInfo);
[DllImport("crypt32.dll", SetLastError=true)]
public static extern IntPtr CertFindCertificateInStore(
IntPtr hCertStore,
uint dwCertEncodingType,
uint dwFindFlags,
uint dwFindType,
[In, MarshalAs(UnmanagedType.LPWStr*)]String pszFindString,
IntPtr pPrevCertCntxt) ;
[DllImport("crypt32.dll", SetLastError=true)]
public static extern bool CertFreeCertificateContext(
IntPtr hCertStore) ;
[DllImport("crypt32.dll", CharSet=CharSet.Auto, SetLastError=true)]
//overloaded
public static extern IntPtr CertOpenStore(
[MarshalAs(UnmanagedType.LPStr*)] String storeProvider,
uint dwMsgAndCertEncodingType,
IntPtr hCryptProv,
uint dwFlags,
String cchNameString) ;
[DllImport("crypt32.dll", SetLastError=true)]
public static extern bool CertCloseStore(
IntPtr hCertStore,
uint dwFlags) ;
}

}

HTH
rawCoder
"rawCoder" <ra******@hotmail.com> wrote in message
news:O2**************@TK2MSFTNGP12.phx.gbl...
Hi All,

I have a *.cer file, a public key of some one and I want to encrypt some
thing using this public key.

Can someone point me to a sample code for Encrypting some file using
X509Certificate ( *.cer file ) so that it can be used to email as
attachment.

The real part is Encrypting using X509Certificate and CryptoServiceProvider.
Am I one the right track ?

Any help is appreciated.

Thanx in advance

rawCoder

Nov 17 '05 #2
In case you are still interested. Here is an article and some sample code
http://www.codeproject.com/useritems...ertificate.asp

Nov 17 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Gordan | last post by:
Hi, I looked through the manual and did some Googling but I couldn't find any functions/classes that would allow me to encrypt/decrypt files with PHP. Here's what I want to do: I have a certain...
5
by: Jerry | last post by:
Hi, I am writing a Java Chatroom application that will implement encryption of messages using the RSA algorithm using the BigInteger class. It uses socket connections to exchange messages. I...
2
by: rawCoder | last post by:
Hi All, I have a *.cer file, a public key of some one and I want to encrypt some thing using this public key. Can someone point me to a sample code for Encrypting some file using...
24
by: Christopher Benson-Manica | last post by:
Is there anything wrong with my attempt (below) at implementing something resembling a smart pointer? template < class T > class SmartPointer { private: T *t; public:
4
by: Gactimus | last post by:
Here is a program that encodes and decodes a text file. What I need to do is write a C++ program that requests 3 different file names. One filename is for the source file to be encoded, another is...
0
by: roshmita | last post by:
The caching application block supports encryption of data in the Data Backing Store.Is it possible to encrypt the data in the memory(cache) using this block?If it is possible please tell me the...
1
by: Duncan Winn | last post by:
Is there any way to encrypt XML files using c# Thanks
0
by: no game | last post by:
Is there a sample code (better in C#) using Crypto API library that encrypt data using public and private key that load from .pfx and .cer file, and encrypt and decrypt data, and sign data? I...
5
by: Kay-Christian Wessel | last post by:
I'm trying to use a certificate on my pocket PC device to access a WebService using VS2003/VS2005. I've been able to read the certificate of my Certificate Store, but I don't know how to use it...
2
by: David T. Ashley | last post by:
I have plain vanilla PHP (bcmath is the only thing special I'm aware of). I don't have mcrypt compiled in. Are there any functions that can be used for reversible encryption? (I have thought...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.