Encryption using X509Certificate

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • rawCoder

    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 CryptoServicePr ovider.

    Am I one the right track ?

    Any help is appreciated.

    Thanx in advance

    rawCoder


  • rawCoder

    #2
    Re: Encryption using X509Certificate

    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) ;
    RSACryptoServic eProvider rsa = CertUtil.GetCer tPublicKey(cert ­);
    Console.WriteLi ne(rsa.ToXmlStr ­ing(false));

    /// CertUtil helper Class.
    using System;
    using System.Security .Cryptography;
    using System.Runtime. InteropServices ­;
    using System.Security .Cryptography.X ­509Certificate s;


    namespace WSESimpleTCPDLL
    {
    [StructLayout(La youtKind.Seque­ ntial)]
    public struct PUBKEYBLOBHEADE RS
    {
    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_STO RE_CURRENT_USER = 0x00010000;
    const uint CERT_STORE_READ ONLY_FLAG = 0x00008000;
    const uint CERT_STORE_OPEN _EXISTING_FLAG = 0x00004000;
    const uint CERT_FIND_SUBJE CT_STR = 0x00080007;
    const uint X509_ASN_ENCODI NG = 0x00000001;
    const uint PKCS_7_ASN_ENCO DING = 0x00010000;
    const uint RSA_CSP_PUBLICK EYBLOB = 19;
    const int AT_KEYEXCHANGE = 1; //keyspec values
    const int AT_SIGNATURE = 2;
    static uint ENCODING_TYPE = PKCS_7_ASN_ENCO DING | X509_ASN_ENCODI NG ;


    private CertUtil()
    {
    }


    public static RSACryptoServic eProvider GetCertPublicKe y(X509Certifica ­te
    cert)
    {
    byte[] publickeyblob ;
    byte[] encodedpubkey = cert.GetPublicK ey(); //asn.1 encoded public key


    uint blobbytes = 0;


    if(Win32.CryptD ecodeObject(ENC ­ODING_TYPE, RSA_CSP_PUBLICK EYBLOB,
    encodedpubkey, (uint)encodedpu bkey.Length, 0, null, ref blobbytes))
    {
    publickeyblob = new byte[blobbytes];
    Win32.CryptDeco deObject(ENCODI ­NG_TYPE, RSA_CSP_PUBLICK EYBLOB,
    encodedpubkey, (uint)encodedpu bkey.Length, 0, publickeyblob, ref blobbytes);
    }
    else
    {
    throw new Exception("Coul d not decode publickeyblob from certificate
    publickey") ;
    }


    PUBKEYBLOBHEADE RS pkheaders = new PUBKEYBLOBHEADE RS() ;
    int headerslength = Marshal.SizeOf( pkheaders);
    IntPtr buffer = Marshal.AllocHG lobal( headerslength);
    Marshal.Copy( publickeyblob, 0, buffer, headerslength );
    pkheaders = (PUBKEYBLOBHEAD ERS) Marshal.PtrToSt ructure( buffer,
    typeof(PUBKEYBL OBHEADERS) );
    Marshal.FreeHGl obal( buffer );


    //----- Get public exponent -------------
    byte[] exponent = BitConverter.Ge tBytes(pkheader ­s.pubexp);
    //little-endian ordered
    Array.Reverse(e xponent); //convert to big-endian order


    //----- Get modulus -------------
    int modulusbytes = (int)pkheaders. bitlen/8 ;
    byte[] modulus = new byte[modulusbytes];
    try
    {
    Array.Copy(publ ickeyblob, headerslength, modulus, 0, modulusbytes);
    Array.Reverse(m odulus); //convert from little to big-endian ordering.
    }
    catch(Exception )
    {
    throw new Exception("Prob lem getting modulus from publickeyblob") ;
    }


    RSAParameters parms = new RSAParameters() ;
    parms.Modulus = modulus;
    parms.Exponent = exponent;
    RSACryptoServic eProvider rsa = new RSACryptoServic eProvider();
    rsa.ImportParam eters(parms);
    return rsa;
    }
    }



    }


    //// Win32 Helpers
    using System;
    using System.Runtime. InteropServices ­;
    using System.Componen tModel;
    using System.Collecti ons;
    using System.Text;

    namespace WSESimpleTCPDLL
    {
    public class Win32
    {
    [DllImport("cryp t32.dll")]
    public static extern bool CryptDecodeObje ct(
    uint CertEncodingTyp e,
    uint lpszStructType,
    byte[] pbEncoded,
    uint cbEncoded,
    uint flags,
    [In, Out] byte[] pvStructInfo,
    ref uint cbStructInfo);


    [DllImport("cryp t32.dll", SetLastError=tr ue)]
    public static extern IntPtr CertFindCertifi cateInStore(
    IntPtr hCertStore,
    uint dwCertEncodingT ype,
    uint dwFindFlags,
    uint dwFindType,
    [In, MarshalAs(Unman agedType.LPWStr ­)]String pszFindString,
    IntPtr pPrevCertCntxt) ;


    [DllImport("cryp t32.dll", SetLastError=tr ue)]
    public static extern bool CertFreeCertifi cateContext(
    IntPtr hCertStore) ;


    [DllImport("cryp t32.dll", CharSet=CharSet .Auto, SetLastError=tr ue)]
    //overloaded
    public static extern IntPtr CertOpenStore(
    [MarshalAs(Unman agedType.LPStr­ )] String storeProvider,
    uint dwMsgAndCertEnc odingType,
    IntPtr hCryptProv,
    uint dwFlags,
    String cchNameString) ;


    [DllImport("cryp t32.dll", SetLastError=tr ue)]
    public static extern bool CertCloseStore(
    IntPtr hCertStore,
    uint dwFlags) ;
    }



    }

    HTH
    rawCoder
    "rawCoder" <rawCoder@hotma il.com> wrote in message
    news:O2VLKRJVFH A.3076@TK2MSFTN GP12.phx.gbl...[color=blue]
    > 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[/color]
    CryptoServicePr ovider.[color=blue]
    >
    > Am I one the right track ?
    >
    > Any help is appreciated.
    >
    > Thanx in advance
    >
    > rawCoder
    >
    >[/color]


    Comment

    • Klassy

      #3
      Re: Encryption using X509Certificate

      In case you are still interested. Here is an article and some sample code


      Comment

      Working...