473,372 Members | 824 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,372 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
Jul 21 '05 #1
2 5855
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

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

Jul 21 '05 #3

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

Similar topics

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...
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...
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,...
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: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...

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.