Reads and decrypts a CMS enveloped-data object writing data directly into a string instead of a file.
VB6/VBA
Debug.Print "Testing CMS_ReadEnvDataToString ..." Dim strPrivateKey As String Dim strFileIn As String Dim strDataOut As String Dim nLen As Long Dim strCertFile As String strFileIn = "cms2bobandcarl.p7m" ' First, Bob reads his private key into a string strPrivateKey = rsaReadPrivateKey("BobPrivRSAEncrypt.epk", "password") If Len(strPrivateKey) = 0 Then MsgBox "Cannot read private key" Exit Sub End If ' Query the size of encrypted content (no need for an output buffer) nLen = CMS_QueryEnvData("", 0, strFileIn, "sizeofEncryptedContent", 0) Debug.Print "CMS_QueryEnvData returns " & nLen If nLen <= 0 Then GoTo CleanUp End If ' Pre-dimension string and read in the plaintext ' The final plaintext will always be shorter than the encrypted content. strDataOut = String(nLen, " ") nLen = CMS_ReadEnvDataToString(strDataOut, nLen, _ strFileIn, "", strPrivateKey, 0) Debug.Print "CMS_ReadEnvDataToString returns " & nLen If nLen > 0 Then ' Fix correct size for final, unpadded plaintext strDataOut = Left(strDataOut, nLen) Debug.Print "Plaintext is '" & strDataOut & "'" End If CleanUp: WIPE_String strPrivateKey, Len(strPrivateKey) strPrivateKey = ""
Output
Testing CMS_ReadEnvDataToString ... CMS_QueryEnvData returns 32 CMS_ReadEnvDataToString returns 28 Plaintext is 'This is some sample content.'
VB.NET
Console.WriteLine("Testing CMS_ReadEnvDataToString ...")
Dim sbPrivateKey As StringBuilder
Dim strFileIn As String
Dim strDataOut As String
''Dim nLen As Integer
Dim strCertFile As String
Dim strSize As String
strFileIn = "cms2bobandcarl.p7m"
' First, Bob reads his private key into a string
sbPrivateKey = Rsa.ReadEncPrivateKey("BobPrivRSAEncrypt.epk", "password")
If sbPrivateKey.Length = 0 Then
MsgBox("Cannot read private key")
Exit Sub
End If
' Query the size of encrypted content (no need for an output buffer)
strSize = Cms.QueryEnvData(strFileIn, "sizeofEncryptedContent", False)
Console.WriteLine("CMS_QueryEnvData returns " & strSize)
If strSize = "0" Then
GoTo CleanUp
End If
' Pre-dimension string and read in the plaintext
' The final plaintext will always be shorter than the encrypted content.
strDataOut = Cms.ReadEnvDataToString(strFileIn, "", sbPrivateKey.ToString, 0)
Console.WriteLine("CMS_ReadEnvDataToString returns " & strDataOut.Length)
If strDataOut.Length > 0 Then
Console.WriteLine("Plaintext is '" & strDataOut & "'")
End If
CleanUp:
Wipe.String(sbPrivateKey)
[Contents]