Retired Microsoft Blog disclaimer

This directory is a mirror of retired "Decrypt My World" MSDN blog and is provided as is. All posting authorship and copyrights belong to respective authors.

Posts on this page:

Original URL: https://blogs.msdn.microsoft.com/alejacma/2009/04/30/do-you-need-help-right-now/
Post name: Do you need help right now?
Original author: Alejandro Campos Magencio
Posting date: 2009-04-30T10:30:00+00:00


Hi all,

I've been quite busy lately and didn't find any free time to post anything or answer all the questions I get on my posts. Really sorry about that.

If you have any issue or question on anything you may find in my blog and you don't get an answer in a reasonable time, I suggest you open a support case with us, Microsoft Technical Support. We will be more than happy to assist you. Thank you.

Regards,

Alex (Alejandro Campos Magencio)

Original URL: https://blogs.msdn.microsoft.com/alejacma/2009/04/01/how-to-get-information-from-a-crl-net/
Post name: How to get information from a CRL (.NET)
Original author: Alejandro Campos Magencio
Posting date: 2009-04-01T05:00:00+00:00


Hi all,


The following C# sample uses CryptoAPI to read the info of a CRL (Certificate Revocation List)stored in a file:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

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

private void getInfoButton_Click(object sender, EventArgs e)
{
// Variables
//
Boolean bResult = false;
IntPtr pvContext = IntPtr.Zero;
Win32.CRL_CONTEXT CRLContext;
Win32.CRL_INFO CRLInfo;
Int32 csz = 0;
StringBuilder psz = null;
IntPtr rgCRLEntry = IntPtr.Zero;
Win32.CRL_ENTRY CRLEntry;
String strSerialNumber = "";
IntPtr pByte = IntPtr.Zero;
Byte bByte = 0;
IntPtr rgExtension = IntPtr.Zero;
Win32.CERT_EXTENSION CRLExtension;
Int32 cbFormat = 0;
StringBuilder pbFormat = null;
String strCRLReasonCode = "";

// Clean screen
//
issuerTextBox.Text = "";
revocationListBox.Items.Clear();

try
{
// Get CRL context
//
bResult = Win32.CryptQueryObject(
Win32.CERT_QUERY_OBJECT_FILE,
fileTextBox.Text,
Win32.CERT_QUERY_CONTENT_FLAG_CRL,
Win32.CERT_QUERY_FORMAT_FLAG_BINARY,
0,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
ref pvContext
);
if (!bResult)
{
throw new Exception("CryptQueryObject error #" + Marshal.GetLastWin32Error());
}

CRLContext = (Win32.CRL_CONTEXT)Marshal.PtrToStructure(pvContext, typeof(Win32.CRL_CONTEXT));

// Get CRL info
//
CRLInfo = (Win32.CRL_INFO)Marshal.PtrToStructure(CRLContext.pCrlInfo, typeof(Win32.CRL_INFO));

// Get CRL issuer
//
csz = Win32.CertNameToStr(
Win32.X509_ASN_ENCODING | Win32.PKCS_7_ASN_ENCODING,
ref CRLInfo.Issuer,
Win32.CERT_X500_NAME_STR,
null,
0
);
if (csz <= 0)
{
throw new Exception("CertNameToStr error #" + Marshal.GetLastWin32Error());
}

psz = new StringBuilder(csz);

csz = Win32.CertNameToStr(
Win32.X509_ASN_ENCODING | Win32.PKCS_7_ASN_ENCODING,
ref CRLInfo.Issuer,
Win32.CERT_X500_NAME_STR,
psz,
csz
);
if (csz <= 0)
{
throw new Exception("CertNameToStr error #" + Marshal.GetLastWin32Error());
}

// Show CRL issuer
//
issuerTextBox.Text = psz.ToString();

// Get revocation list
//
rgCRLEntry = CRLInfo.rgCRLEntry;
for (int i = 0; i < CRLInfo.cCRLEntry; i++)
{
// Get the serial number of one revoked certificate
//
strSerialNumber = "";

CRLEntry = (Win32.CRL_ENTRY)Marshal.PtrToStructure(rgCRLEntry, typeof(Win32.CRL_ENTRY));

pByte = CRLEntry.SerialNumber.pbData;
for (int j = 0; j < CRLEntry.SerialNumber.cbData; j++)
{
bByte = Marshal.ReadByte(pByte);
strSerialNumber = bByte.ToString("X").PadLeft(2, '0') + " " + strSerialNumber;
pByte = (IntPtr)((Int32)pByte + Marshal.SizeOf(typeof(Byte)));
}

// Get the CRL Reason Code of that revoked certificate
//
strCRLReasonCode = "";

rgExtension = Win32.CertFindExtension(
Win32.szOID_CRL_REASON_CODE,
CRLEntry.cExtension,
CRLEntry.rgExtension
);
if (rgExtension.Equals(IntPtr.Zero))
{
throw new Exception("CertFindExtension found no CRL Reason Code");
}

CRLExtension = (Win32.CERT_EXTENSION)Marshal.PtrToStructure(rgExtension, typeof(Win32.CERT_EXTENSION));

// Format that CRL Reason Code so we can show it
//
cbFormat = 0;
pbFormat = null;
bResult = Win32.CryptFormatObject(
Win32.X509_ASN_ENCODING,
0,
0,
IntPtr.Zero,
Win32.szOID_CRL_REASON_CODE,
CRLExtension.Value.pbData,
CRLExtension.Value.cbData,
null,
ref cbFormat
);
if (!bResult)
{
throw new Exception("CryptFormatObject error #" + Marshal.GetLastWin32Error());
}

pbFormat = new StringBuilder(cbFormat);

bResult = Win32.CryptFormatObject(
Win32.X509_ASN_ENCODING,
0,
0,
IntPtr.Zero,
Win32.szOID_CRL_REASON_CODE,
CRLExtension.Value.pbData,
CRLExtension.Value.cbData,
pbFormat,
ref cbFormat
);
if (!bResult)
{
throw new Exception("CryptFormatObject error #" + Marshal.GetLastWin32Error());
}

strCRLReasonCode = pbFormat.ToString();

// Show Serial Number and CRL Reason Code
//
revocationListBox.Items.Add(strSerialNumber + "\t-->\t" + strCRLReasonCode);

// Continue with the next entry in the list
//
rgCRLEntry = (IntPtr)((Int32)rgCRLEntry + Marshal.SizeOf(typeof(Win32.CRL_ENTRY)));
}
}
catch (Exception ex)
{
// Show errors
//
MessageBox.Show(ex.Message);
}
finally
{
// Do some clean up
//
if (!pvContext.Equals(IntPtr.Zero))
{
Win32.CertFreeCRLContext(pvContext);
}
}
}
}
}

public class Win32
{
#region APIs

[DllImport("CRYPT32.DLL", EntryPoint = "CryptQueryObject", CharSet = CharSet.Auto, SetLastError = true)]
public static extern Boolean CryptQueryObject(
Int32 dwObjectType,
[MarshalAs(UnmanagedType.LPWStr)]String pvObject,
Int32 dwExpectedContentTypeFlags,
Int32 dwExpectedFormatTypeFlags,
Int32 dwFlags,
IntPtr pdwMsgAndCertEncodingType,
IntPtr pdwContentType,
IntPtr pdwFormatType,
IntPtr phCertStore,
IntPtr phMsg,
ref IntPtr ppvContext
);

[DllImport("CRYPT32.DLL", EntryPoint = "CertFreeCRLContext", SetLastError = true)]
public static extern Boolean CertFreeCRLContext(
IntPtr pCrlContext
);

[DllImport("CRYPT32.DLL", EntryPoint = "CertNameToStr", CharSet = CharSet.Auto, SetLastError = true)]
public static extern Int32 CertNameToStr(
Int32 dwCertEncodingType,
ref CRYPTOAPI_BLOB pName,
Int32 dwStrType,
StringBuilder psz,
Int32 csz
);

[DllImport("CRYPT32.DLL", EntryPoint = "CertFindExtension", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CertFindExtension(
[MarshalAs(UnmanagedType.LPStr)]String pszObjId,
Int32 cExtensions,
IntPtr rgExtensions
);

[DllImport("CRYPT32.DLL", EntryPoint = "CryptFormatObject", CharSet = CharSet.Auto, SetLastError = true)]
public static extern Boolean CryptFormatObject(
Int32 dwCertEncodingType,
Int32 dwFormatType,
Int32 dwFormatStrType,
IntPtr pFormatStruct,
[MarshalAs(UnmanagedType.LPStr)]String lpszStructType,
IntPtr pbEncoded,
Int32 cbEncoded,
StringBuilder pbFormat,
ref Int32 pcbFormat
);

#endregion APIs

#region Structs

[StructLayout(LayoutKind.Sequential)]
public struct CRL_CONTEXT
{
public Int32 dwCertEncodingType;
public IntPtr pbCrlEncoded;
public Int32 cbCrlEncoded;
public IntPtr pCrlInfo;
public IntPtr hCertStore;
}

[StructLayout(LayoutKind.Sequential)]
public struct CRL_INFO
{
public Int32 dwVersion;
public CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm;
public CRYPTOAPI_BLOB Issuer;
public FILETIME ThisUpdate;
public FILETIME NextUpdate;
public Int32 cCRLEntry;
public IntPtr rgCRLEntry;
public Int32 cExtension;
public IntPtr rgExtension;
}

[StructLayout(LayoutKind.Sequential)]
public struct CRYPT_ALGORITHM_IDENTIFIER
{
[MarshalAs(UnmanagedType.LPStr)]public String pszObjId;
public CRYPTOAPI_BLOB Parameters;
}

[StructLayout(LayoutKind.Sequential)]
public struct CRYPTOAPI_BLOB
{
public Int32 cbData;
public IntPtr pbData;
}

[StructLayout(LayoutKind.Sequential)]
public struct FILETIME
{
public Int32 dwLowDateTime;
public Int32 dwHighDateTime;
}

[StructLayout(LayoutKind.Sequential)]
public struct CRL_ENTRY
{
public CRYPTOAPI_BLOB SerialNumber;
public FILETIME RevocationDate;
public Int32 cExtension;
public IntPtr rgExtension;
}

[StructLayout(LayoutKind.Sequential)]
public struct CERT_EXTENSION
{
[MarshalAs(UnmanagedType.LPStr)]public String pszObjId;
public Boolean fCritical;
public CRYPTOAPI_BLOB Value;
}

#endregion Structs

#region Consts

public const Int32 CERT_QUERY_OBJECT_FILE = 0x00000001;
public const Int32 CERT_QUERY_CONTENT_CRL = 3;
public const Int32 CERT_QUERY_CONTENT_FLAG_CRL = 1 << CERT_QUERY_CONTENT_CRL;
public const Int32 CERT_QUERY_FORMAT_BINARY = 1;
public const Int32 CERT_QUERY_FORMAT_BASE64_ENCODED = 2;
public const Int32 CERT_QUERY_FORMAT_ASN_ASCII_HEX_ENCODED = 3;
public const Int32 CERT_QUERY_FORMAT_FLAG_BINARY = 1 << CERT_QUERY_FORMAT_BINARY;
public const Int32 CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED = 1 << CERT_QUERY_FORMAT_BASE64_ENCODED;
public const Int32 CERT_QUERY_FORMAT_FLAG_ASN_ASCII_HEX_ENCODED = 1 << CERT_QUERY_FORMAT_ASN_ASCII_HEX_ENCODED;
public const Int32 CERT_QUERY_FORMAT_FLAG_ALL = CERT_QUERY_FORMAT_FLAG_BINARY | CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED | CERT_QUERY_FORMAT_FLAG_ASN_ASCII_HEX_ENCODED;

public const Int32 X509_ASN_ENCODING = 0x00000001;
public const Int32 PKCS_7_ASN_ENCODING = 0x00010000;

public const Int32 X509_NAME = 7;

public const Int32 CERT_SIMPLE_NAME_STR = 1;
public const Int32 CERT_OID_NAME_STR = 2;
public const Int32 CERT_X500_NAME_STR = 3;

public const String szOID_CRL_REASON_CODE = "2.5.29.21";

#endregion
}


I hope this helps.


Regards,



Alex (Alejandro Campos Magencio)

Original URL: https://blogs.msdn.microsoft.com/alejacma/2009/03/16/how-to-create-a-self-signed-certificate-with-cryptoapi-c/
Post name: How to create a self-signed certificate with CryptoAPI (C++)
Original author: Alejandro Campos Magencio
Posting date: 2009-03-16T08:36:00+00:00


Hi all,


The following C++ sample shows how to use CertCreateSelfSignCertificate API to create a self-signed certificate. The private/public key pair will be created in the machine profile and the certificate will be stored in the Trusted Root CA store of that same profile:

#include "stdio.h"
#include "conio.h"
#include "windows.h"
#include "wincrypt.h"
#include "tchar.h"

int SelfSignedCertificateTest()
{
// CREATE KEY PAIR FOR SELF-SIGNED CERTIFICATE IN MACHINE PROFILE

HCRYPTPROV hCryptProv = NULL;
HCRYPTKEY hKey = NULL;

__try
{
// Acquire key container
_tprintf(_T("CryptAcquireContext... "));
if (!CryptAcquireContext(&hCryptProv, _T("alejacma"), NULL, PROV_RSA_FULL, CRYPT_MACHINE_KEYSET))
{
// Error
_tprintf(_T("Error 0x%x\n"), GetLastError());

// Try to create a new key container
_tprintf(_T("CryptAcquireContext... "));
if (!CryptAcquireContext(&hCryptProv, _T("alejacma"), NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET | CRYPT_MACHINE_KEYSET))
{
// Error
_tprintf(_T("Error 0x%x\n"), GetLastError());
return 0;
}
else
{
_tprintf(_T("Success\n"));
}
}
else
{
_tprintf(_T("Success\n"));
}

// Generate new key pair
_tprintf(_T("CryptGenKey... "));
if (!CryptGenKey(hCryptProv, AT_SIGNATURE, 0x08000000 /*RSA-2048-BIT_KEY*/, &hKey))
{
// Error
_tprintf(_T("Error 0x%x\n"), GetLastError());
return 0;
}
else
{
_tprintf(_T("Success\n"));
}
}
__finally
{
// Clean up

if (hKey)
{
_tprintf(_T("CryptDestroyKey... "));
CryptDestroyKey(hKey);
_tprintf(_T("Success\n"));
}
if (hCryptProv)
{
_tprintf(_T("CryptReleaseContext... "));
CryptReleaseContext(hCryptProv, 0);
_tprintf(_T("Success\n"));
}
}

// CREATE SELF-SIGNED CERTIFICATE AND ADD IT TO ROOT STORE IN MACHINE PROFILE

PCCERT_CONTEXT pCertContext = NULL;
BYTE *pbEncoded = NULL;
HCERTSTORE hStore = NULL;
HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProvOrNCryptKey = NULL;
BOOL fCallerFreeProvOrNCryptKey = FALSE;

__try
{
// Encode certificate Subject
LPCTSTR pszX500 = _T("CN=Alejacma, T=Test");
DWORD cbEncoded = 0;
_tprintf(_T("CertStrToName... "));
if (!CertStrToName(X509_ASN_ENCODING, pszX500, CERT_X500_NAME_STR, NULL, pbEncoded, &cbEncoded, NULL))
{
// Error
_tprintf(_T("Error 0x%x\n"), GetLastError());
return 0;
}
else
{
_tprintf(_T("Success\n"));
}

_tprintf(_T("malloc... "));
if (!(pbEncoded = (BYTE *)malloc(cbEncoded)))
{
// Error
_tprintf(_T("Error 0x%x\n"), GetLastError());
return 0;
}
else
{
_tprintf(_T("Success\n"));
}

_tprintf(_T("CertStrToName... "));
if (!CertStrToName(X509_ASN_ENCODING, pszX500, CERT_X500_NAME_STR, NULL, pbEncoded, &cbEncoded, NULL))
{
// Error
_tprintf(_T("Error 0x%x\n"), GetLastError());
return 0;
}
else
{
_tprintf(_T("Success\n"));
}

// Prepare certificate Subject for self-signed certificate
CERT_NAME_BLOB SubjectIssuerBlob;
memset(&SubjectIssuerBlob, 0, sizeof(SubjectIssuerBlob));
SubjectIssuerBlob.cbData = cbEncoded;
SubjectIssuerBlob.pbData = pbEncoded;

// Prepare key provider structure for self-signed certificate
CRYPT_KEY_PROV_INFO KeyProvInfo;
memset(&KeyProvInfo, 0, sizeof(KeyProvInfo));
KeyProvInfo.pwszContainerName = _T("alejacma");
KeyProvInfo.pwszProvName = NULL;
KeyProvInfo.dwProvType = PROV_RSA_FULL;
KeyProvInfo.dwFlags = CRYPT_MACHINE_KEYSET;
KeyProvInfo.cProvParam = 0;
KeyProvInfo.rgProvParam = NULL;
KeyProvInfo.dwKeySpec = AT_SIGNATURE;

// Prepare algorithm structure for self-signed certificate
CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm;
memset(&SignatureAlgorithm, 0, sizeof(SignatureAlgorithm));
SignatureAlgorithm.pszObjId = szOID_RSA_SHA1RSA;

// Prepare Expiration date for self-signed certificate
SYSTEMTIME EndTime;
GetSystemTime(&EndTime);
EndTime.wYear += 5;

// Create self-signed certificate
_tprintf(_T("CertCreateSelfSignCertificate... "));
pCertContext = CertCreateSelfSignCertificate(NULL, &SubjectIssuerBlob, 0, &KeyProvInfo, &SignatureAlgorithm, 0, &EndTime, 0);
if (!pCertContext)
{
// Error
_tprintf(_T("Error 0x%x\n"), GetLastError());
return 0;
}
else
{
_tprintf(_T("Success\n"));
}

// Open Root cert store in machine profile
_tprintf(_T("CertOpenStore... "));
hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTEM_STORE_LOCAL_MACHINE, L"Root");
if (!hStore)
{
// Error
_tprintf(_T("Error 0x%x\n"), GetLastError());
return 0;
}
else
{
_tprintf(_T("Success\n"));
}

// Add self-signed cert to the store
_tprintf(_T("CertAddCertificateContextToStore... "));
if (!CertAddCertificateContextToStore(hStore, pCertContext, CERT_STORE_ADD_REPLACE_EXISTING, 0))
{
// Error
_tprintf(_T("Error 0x%x\n"), GetLastError());
return 0;
}
else
{
_tprintf(_T("Success\n"));
}

// Just for testing, verify that we can access self-signed cert's private key
DWORD dwKeySpec;
_tprintf(_T("CryptAcquireCertificatePrivateKey... "));
if (!CryptAcquireCertificatePrivateKey(pCertContext, 0, NULL, &hCryptProvOrNCryptKey, &dwKeySpec, &fCallerFreeProvOrNCryptKey))
{
// Error
_tprintf(_T("Error 0x%x\n"), GetLastError());
return 0;
}
else
{
_tprintf(_T("Success\n"));
}
}
__finally
{
// Clean up

if (!pbEncoded) {
_tprintf(_T("free... "));
free(pbEncoded);
_tprintf(_T("Success\n"));
}

if (hCryptProvOrNCryptKey)
{
_tprintf(_T("CryptReleaseContext... "));
CryptReleaseContext(hCryptProvOrNCryptKey, 0);
_tprintf(_T("Success\n"));
}

if (pCertContext)
{
_tprintf(_T("CertFreeCertificateContext... "));
CertFreeCertificateContext(pCertContext);
_tprintf(_T("Success\n"));
}

if (hStore)
{
_tprintf(_T("CertCloseStore... "));
CertCloseStore(hStore, 0);
_tprintf(_T("Success\n"));
}
}
}

int _tmain(int argc, _TCHAR* argv[])
{
SelfSignedCertificateTest();

_tprintf(_T("<< Press any key>>\n"));
_getch();
return 0;
}



I hope this helps.


Regards,



Alex (Alejandro Campos Magencio)

Original URL: https://blogs.msdn.microsoft.com/alejacma/2009/03/12/how-to-get-lastlogon-property-for-all-users-in-a-domain-vbscript/
Post name: How to get LastLogon property for all users in a Domain (VBScript)
Original author: Alejandro Campos Magencio
Posting date: 2009-03-12T06:05:00+00:00


Hi all,


The following VBScript sample retrieves all users in Active Directory that haven't ever logged on the domain, or haven't logged on for at least maxDays (an argument passed to the script):

On Error Resume Next

' Constants
'
Const ONE_HUNDRED_NANOSECOND = .000000100
Const SECONDS_IN_DAY = 86400

' Get Max Days as an argument passed to the script
'
If Not Wscript.Arguments.Count() = 1 Then
Wscript.Echo "Syntax error, argument required"
Wscript.Quit
End If

maxDays = CInt(Wscript.Arguments(0))

' Create the log file
'
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = objFSO.CreateTextFile(GetPath() & "log.txt", 8, true)

' Get the root of the domain
'
Set objRoot = Getobject("LDAP://RootDSE")
strRoot = objRoot.Get("defaultnamingcontext")
Set objRoot = Nothing

' Create connection
'
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"

' Create command
'
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
objCommand.Properties("Page Size") = 1000

' Execute command to get all DCs in the domain
'
objCommand.CommandText = "<LDAP://OU=Domain Controllers," & strRoot & ">;(objectcategory=computer);name;onelevel"
Set objRecordSet = objCommand.Execute

'LogData("INFO: There are " & objRecordSet.RecordCount & " Domain Controllers.")

' Execute command to get all users in the domain
'
objCommand.CommandText = "<LDAP://" & strRoot & ">;(&(objectclass=user)(objectcategory=person));adspath,distinguishedname,sAMAccountName;subtree"
Set objRecordSet2 = objCommand.Execute

'LogData("INFO: There are " & objRecordSet2.RecordCount & " users.")

' Get the LastLogon for each user in each DC
'
Do Until objRecordSet2.EOF

' Get the LastLogon for one user in each DC, and get the maximum
'
objRecordSet.MoveFirst
maxDate = 0
Do Until objRecordSet.EOF

' Execute command to get LastLogon for the user in one DC
'
LdapPath = "LDAP://" & objRecordSet.Fields("name").Value & "/" & Replace(objRecordSet2.Fields("distinguishedname").Value, "/", "\/")
set objUser = GetObject(LdapPath)

' Check for errors executing the command
'
if Err.Number <> 0 Then
' Error
'
LogData("INFO: LDAP Path = " & LdapPath)
Select Case Err.Number
Case &H8007203A
Err.Description = """The server is not operational"""
Case &H80005000
Err.Description = """An invalid ADSI pathname was passed"""
Case Else
Err.Description = ""
End Select
LogData("ERROR: " & Err.Number & " " & Err.Description)
Else
' No error
'
' Get the LastLogon
'
set objLastLogon = objUser.LastLogon
myDate = 0
If Not(IsNull(objLastLogon) Or IsEmpty(objLastLogon)) Then
myDate = MakeDate(objLastLogon)
End If

' See if it's the maximum
'
If myDate > maxDate Then
maxDate = myDate
End If

End If

' Move on to the next DC
'
Err.Clear
set objUser = nothing
set objLastLogon = nothing
objRecordSet.MoveNext

Loop

' Show the maximum LastLogon for the user
'
If maxDate = 0 Then
LogData("INFO: User """ & objRecordSet2.Fields("sAMAccountName").Value & """ never logged on.")
ElseIf (Date() - maxDate) > maxDays Then
LogData("INFO: User """ & objRecordSet2.Fields("sAMAccountName").Value & """ logged on " & maxDate)
End If

' Move on to the next user
'
objRecordSet2.MoveNext

Loop

' Close everything
'
objRecordSet.Close
Set objRecordSet = Nothing
objRecordSet2.Close
Set objRecordSet2 = Nothing
Set objCommand = Nothing
objConnection.Close
Set objConnection = Nothing

' We are done!
'
Wscript.Echo "All Done!"

'================================================================
' HELPER FUNCTIONS
'================================================================

' Get script's path
'
Function GetPath()

Dim path
path = WScript.ScriptFullName
GetPath = Left(path, InStrRev(path, "\"))

End Function

' Write data to log file
'
Sub LogData(data)

objLogFile.writeline Now() & ", " & data

End Sub

' Convert long integer to a date
'
Function MakeDate(oLInt)

Set objShell = CreateObject("Wscript.Shell")

lngBiasKey = objShell.RegRead("HKLM\System\CurrentControlSet\Control\TimeZoneInformation\ActiveTimeBias")

If UCase(TypeName(lngBiasKey)) = "LONG" Then
glngBias = lngBiasKey

ElseIf UCase(TypeName(lngBiasKey)) = "VARIANT()" Then
glngBias = 0

For k = 0 To UBound(lngBiasKey)
glngBias = lngBias + (lngBiasKey(k) * 256^k)
Next
End If

dtmDate = #1/1/1601# + (((oLInt.HighPart * (2 ^ 32)) + oLInt.LowPart) / 600000000 - glngBias) / 1440

MakeDate = dtmDate

End Function



I hope this helps.


Regards,



Alex (Alejandro Campos Magencio)


Original URL: https://blogs.msdn.microsoft.com/alejacma/2009/02/20/how-to-create-a-certificate-request-with-certenroll-asp/
Post name: How to create a certificate request with CertEnroll (ASP)
Original author: Alejandro Campos Magencio
Posting date: 2009-02-20T07:05:00+00:00


Hi all,


The other day I posted a Javascript sample which shows how to use CertEnroll COM component to create a certificate request and install the response from the CA (Certificate Authority): How to create a certificate request with CertEnroll (JavaScript).


The installation part of that sample assumed that we got a Base64 textwith the response from the CA. But what if we i.e. send the request to a server, the server gets a .p7b or .cer binary file with the response from the CA, and we want to install the response on the client who requested the cert on the first place?


The following ASP sample shows how to install on the client the .p7b/.cer binary file that the server got with the response from the CA:


<%
' Convert binary to Base64
'
Function BinaryToBase64(binary)
' Create temporary node with Base64 data type
Set oXmlDom = CreateObject("microsoft.xmldom")
Set oElement = oXmlDom.createElement("tmp")
oElement.dataType = "bin.base64"
' Set bytes, get encoded String
oElement.nodeTypedValue = binary
BinaryToBase64 = oElement.text
End Function

' Read file into buffer
'
Function ReadBinaryFile(FileName)
Const adTypeBinary = 1
'Create Stream object
Dim BinaryStream
Set BinaryStream = CreateObject("ADODB.Stream")
'Specify stream type - we want To get binary data.
BinaryStream.Type = adTypeBinary
'Open the stream
BinaryStream.Open
'Load the file data from disk To stream object
BinaryStream.LoadFromFile FileName
'Open the stream And get binary data from the object
ReadBinaryFile = BinaryStream.Read
End Function

' Read binary file as Base64
'
FileName = "C:\temp\certnew.p7b"
'FileName = "C:\temp\certnew.cer"
sPKCS7 = BinaryToBase64(ReadBinaryFile(FileName))

' Be careful with line feeds in Base64 string
'
strings = split(sPKCS7, chr(10))
sPKCS7 = """"
for i = 0 to ubound(strings) - 1
sPKCS7 = sPKCS7 + strings(i) + """ + """
next
sPKCS7 = sPKCS7 + strings(i) + """"

%>

<html>
<head>
<title>Certificate Request test</title>
</head>
<body>
<object id="objCertEnrollClassFactory" classid="clsid:884e2049-217d-11da-b2a4-000e7bbb2b09"></object>
<script language="javascript">

function InstallCert()
{
document.write("<br>Installing certificate...");

try {
// Variables
var objEnroll = objCertEnrollClassFactory.CreateObject("X509Enrollment.CX509Enrollment")

objEnroll.Initialize(1); // ContextUser
objEnroll.InstallResponse(4, <%=sPKCS7%>, 1, ""); // AllowUntrustedRoot = 4, XCN_CRYPT_STRING_BASE64 = 1
}
catch (ex) {
document.write("<br>" + ex.description);
return false;
}

document.write("<br>Done!");

return true;
}

InstallCert();

</script>

</body>
</html>


I hope this helps.


Regards,



Alex (Alejandro Campos Magencio)