473,396 Members | 2,121 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,396 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 21 '05 #1
2 6531
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 21 '05 #2
In case you are still interested. Here is an article and some sample code
http://www.codeproject.com/useritems...ertificate.asp

Nov 21 '05 #3

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

Similar topics

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...
1
by: Joe Kinsella | last post by:
I'm porting a small piece of Java that will fetch HTML from a secured web page. The Java code was purposely written to accept any client certificate - even out of date certificates. This was...
6
by: Mattia Saccotelli | last post by:
Hi I would like to encrypt data using AES (Rijndael) algorithm, providing as the key the key from a given certificate. Just for testing I'm using the public key.. Shouldn't I use the private...
3
by: Charles Denny | last post by:
I'm trying to call CertFindCertificateInStore to find all certificates in the store that have the Code Signing enhanced key usage. I'm running into problems marshalling the array of OIDs in...
0
by: Krishna | last post by:
Well, I got it working when running against my test server (IIS5 W2K svr, I will attach a sample of the code at the bottom of this message), but now I'm connecting to our client (Apache) I'm...
2
by: Ed Glunz | last post by:
I'm having some difficulty finding the information I need. Maybe someone can point me in the right direction. I need to call methods on a web service defined by one of our vendors. They require,...
0
by: Anonieko | last post by:
..NET 1.0 /1.1 version: ====================== using System.Net; using System.Security.Cryptography.X509Certificates; // ... private void MethodToAccessSSL() {
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 G | last post by:
My company has a Webservice that is currently running in production. It is secured using SSL and clients are authenticated using X509 certificates. I am able to consume the Webservice methods in...
0
by: BillE | last post by:
VS2005 VB.net I'm using the HTTPWebRequest class to connect to a web site with SSL. I first manually connected to the site and installed the certificate on my computer, and then use the...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.