CKR_BUFFER_TOO_SMALL = 0x00000150 - c#

I want to PInvoke C_Encrypt() "pkcs#11" from a .dll :
[DllImport("cryptoki.dll", SetLastError = true)]
private static extern UInt32 C_Encrypt(CK_SESSION_HANDLE hSession,IntPtr pData,CK_ULONG ulDataLen,out IntPtr pEncryptedData,out CK_ULONG pulEncryptedData);
/*
.... Main
in which I initialize the encryption parametrs with C_EncyptInit
*/
CK_BYTE[] text = new CK_BYTE[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x08, 0x09 };
System.UInt32 t, tt = (System.UInt32)text.Length;
IntPtr pdata = Marshal.AllocHGlobal(text.Length);
Marshal.Copy(text, 0, pdata, text.Length);
IntPtr chif = IntPtr.Zero;
tt = (System.UInt32)Marshal.SizeOf(pdata);
rv = C_Encrypt(h, pdata, tt, out chif, out t);
help please

There's a variety of different problems here.
Your P/Invoke signature is wrong. The final two parameters are not out parameters. The C_Encrypt function will write the encrypted data to those parameters, but you need to allocate and pass them yourself.
You need to allocate data for chif, and then pass the size that you allocated for chif as the final param t. This is the root cause of the error that you're seeing.
Nit: Your variable names are confusing, and you seem to have mixed up tt and t somewhere, since you assign to tt twice.

I resolved the problem By my self:
[DllImport("D:/Program Files/Eracom/ProtectToolkit C SDK/bin/sw/cryptoki.dll", SetLastError = true)]
private static extern UInt32 C_Encrypt(CK_SESSION_HANDLE hSession, CK_BYTE[] pData, CK_ULONG ulDataLen, CK_BYTE[] pEncryptedData,ref CK_ULONG pulEncryptedData);
enjoy

Related

C# Pinvoke Delphi ShortString System.AccessViolationException

My client just sent me a delphi dll to be consumed for my asp.net app, and below is the dll's signature:
function GerarChave(pChave: ShortString; pData: ShortString; pAcao: ShortString): PAnsiChar; stdcall;
How should I call it? I've tried everything like
[DllImport("CEIINT.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "GerarChave")]
public static extern string GerarChave([MarshalAs(UnmanagedType.BStr)]string pChave, [MarshalAs(UnmanagedType.BStr)]string pData, [MarshalAs(UnmanagedType.BStr)]string pAcao);
string chave = "ABC123";
string data = "19/09/2019";
string acao = "0";
GerarChave(chave, data, acao);
but I always get a System.AccessViolationException error which says:
System.AccessViolationException... Attempted to read or write protected memory. This is often an indication that other memory is corrupt
Could anybody help me please? Thanks in advance!
Like David Heffernan said, you should try to get back to your client to request a DLL with more interoperable types.
If you have no other choice you could try to do the conversions manually, first by changing the signature to an byte array:
[DllImport("CEIINT.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "GerarChave")]
public static extern string GerarChave(
[MarshalAs(UnmanagedType.ByValArray, SizeConst=256)] byte[] pChave,
[MarshalAs(UnmanagedType.ByValArray, SizeConst=256)] byte[] pData,
[MarshalAs(UnmanagedType.ByValArray, SizeConst=256)] byte[] pAcao);
Then define the following method to convert a string to a Delphi ShortString:
public byte[] GetDelphiShortString(string str)
{
var bytes = new byte[256];
bytes[0] = (byte)Encoding.Default.GetBytes(str, 0, str.Length, bytes, 1);
return bytes;
}
Finally, you should be able to call the Delphi function via:
GerarChave(GetDelphiShortString(chave), GetDelphiShortString(data), GetDelphiShortString(acao));

Send raw data to print not working

I want to send raw data to print, avoiding printer selection (fast print).
I am trying to use this helper provided by Microsoft: https://support.microsoft.com/en-us/kb/322091#top
However, when I call to the method:
RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, s);
My printer starts to works (makes some noise) but It never takes the white paper and starts to print.
I have tried it with my two printers and the behavior is the same in both printers. Also I discard the possibility that the printers are broken because I can print other documents.
What can be wrong?
Try this:
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class RawPrinterHelper
{
// Structure and API declarions:
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public class DOCINFOA
{
[MarshalAs(UnmanagedType.LPStr)] public string pDocName;
[MarshalAs(UnmanagedType.LPStr)] public string pOutputFile;
[MarshalAs(UnmanagedType.LPStr)] public string pDataType;
}
[DllImport("winspool.Drv", EntryPoint="OpenPrinterA", SetLastError=true, CharSet=CharSet.Ansi, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);
[DllImport("winspool.Drv", EntryPoint="ClosePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint="StartDocPrinterA", SetLastError=true, CharSet=CharSet.Ansi, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool StartDocPrinter( IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
[DllImport("winspool.Drv", EntryPoint="EndDocPrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool EndDocPrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint="StartPagePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool StartPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint="EndPagePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool EndPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint="WritePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten );
// SendBytesToPrinter()
// When the function is given a printer name and an unmanaged array
// of bytes, the function sends those bytes to the print queue.
// Returns true on success, false on failure.
public static bool SendBytesToPrinter( string szPrinterName, IntPtr pBytes, Int32 dwCount)
{
Int32 dwError = 0, dwWritten = 0;
IntPtr hPrinter = new IntPtr(0);
DOCINFOA di = new DOCINFOA();
bool bSuccess = false; // Assume failure unless you specifically succeed.
di.pDocName = "My C#.NET RAW Document";
di.pDataType = "RAW";
// Open the printer.
if( OpenPrinter( szPrinterName.Normalize(), out hPrinter, IntPtr.Zero ) )
{
// Start a document.
if( StartDocPrinter(hPrinter, 1, di) )
{
// Start a page.
if( StartPagePrinter(hPrinter) )
{
// Write your bytes.
bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
}
// If you did not succeed, GetLastError may give more information
// about why not.
if( bSuccess == false )
{
dwError = Marshal.GetLastWin32Error();
}
return bSuccess;
}
public static bool SendFileToPrinter( string szPrinterName, string szFileName )
{
// Open the file.
FileStream fs = new FileStream(szFileName, FileMode.Open);
// Create a BinaryReader on the file.
BinaryReader br = new BinaryReader(fs);
// Dim an array of bytes big enough to hold the file's contents.
Byte []bytes = new Byte[fs.Length];
bool bSuccess = false;
// Your unmanaged pointer.
IntPtr pUnmanagedBytes = new IntPtr(0);
int nLength;
nLength = Convert.ToInt32(fs.Length);
// Read the contents of the file into the array.
bytes = br.ReadBytes( nLength );
// Allocate some unmanaged memory for those bytes.
pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
// Copy the managed byte array into the unmanaged array.
Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
// Send the unmanaged bytes to the printer.
bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
// Free the unmanaged memory that you allocated earlier.
Marshal.FreeCoTaskMem(pUnmanagedBytes);
return bSuccess;
}
public static bool SendStringToPrinter( string szPrinterName, string szString )
{
IntPtr pBytes;
Int32 dwCount;
// How many characters are in the string?
// Fix from Nicholas Piasecki:
// dwCount = szString.Length;
dwCount = (szString.Length + 1) * Marshal.SystemMaxDBCSCharSize;
// Assume that the printer is expecting ANSI text, and then convert
// the string to ANSI text.
pBytes = Marshal.StringToCoTaskMemAnsi(szString);
// Send the converted ANSI string to the printer.
SendBytesToPrinter(szPrinterName, pBytes, dwCount);
Marshal.FreeCoTaskMem(pBytes);
return true;
}
}
Fran_gg7, I had the same issue recently. Firstly, turn on the persistence of documents on the printer. This will allow you to see if the printer successfully received the print request.
You will see items in the printer queue and they will remain there.
In my scenario the print request was correctly being sent to the printer, however I was testing it on a laser printer that ultimately was unable to interpret the raw string data I was passing to it.
I tested the same output on a label printer that could understand the ZPL (zebra programming language) I was passing it and boom it worked fine.
Have a look at this for a detailed explanation
Hope this helps.
In cases where you are using the MSDN example from here https://support.microsoft.com/en-us/kb/322091#top but are trying to use an array of bytes instead of a string or file... This may help
public static void SendBytesToLocalPrinter(byte[] data, string printerName)
{
var size = Marshal.SizeOf(data[0]) * data.Length;
var pBytes = Marshal.AllocHGlobal(size);
try
{
SendBytesToPrinter(printerName, pBytes, size);
}
finally
{
Marshal.FreeCoTaskMem(pBytes);
}
}
This does not change with the byte array encoding. This is useful if you are trying to send some utf8 encoded byte sequences with some binary (ie. image) data mixed in as was the case for our team.
If printing plain text to Dot Matrix using "RawPrinterHelper" Method, it would only work properly for me when I manually added a printer, selected Generic / Text Only, and selected the USB001 port that was assigned to my USB connected printer (okidata in my test). Then RawPrinterHelper.SendStringToPrinter would behave very much like an 'lpd to lpt1:'
Had exactly the same issue with my ZEBRA ZD420 printer.
Sending ZPL string to printer only the data light flashing shortly without printing.
I changed only
Marshal.StringToCoTaskMemAnsi(szString);
to
Marshal.StringToCoTaskMemUTF8(szString);
and it works !

How to print QR Code using Commands with Zebra RW 420 thermal printer via USB in C#

Before you go on and flag my question as a duplicate, believe me, its
not. I have gone through virtually every solution provided here and I
still can't get to get my app to work, so please will you just be nice
and take some time to help me.
Scenario: I have a Zebra RW 420 thermal printer which I would like to use for printing vouchers with a QR Code on them. I am using C# and have followed all the help as given by Scott Chamberlain here and the code here for sending the commands to the printer. I have the EPL2 manual as well as the CPCL, and ZPL reference manuals with a whole lot of stuff on how to format my commands.
Problem:
All the commands I am sending are either printing as plain text replicas of the commands or the printer just hangs with the small message icon showing on its display. I have tried sending the same commands using the Zebra Utilitis and still getting the same result as with my sample app.
Below is the code snippets I have, please do advise me if there are any reference libraries I may require to get this to work.
private void btnPrint_Click(object sender, RoutedEventArgs e)
{
string s = "! 0 200 200 500 1\nB QR 10 100 M 2 U 10\nMA,QR code ABC123\nENDQR\nFORM\nPRINT";
// Have also tried \r\n for the line feeds with the same result.
// Allow the user to select a printer.
PrintDialog pd = new PrintDialog();
if ((bool)pd.ShowDialog())
{
var bytes = Encoding.ASCII.GetBytes(s);
// Send a printer-specific to the printer.
RawPrinterHelper.SendBytesToPrinter(pd.PrintQueue.FullName, bytes, bytes.Length);
}
}
PrinterHelper class as modified by Scott here
public class RawPrinterHelper
{
// Structure and API declarions:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class DOCINFOA
{
[MarshalAs(UnmanagedType.LPStr)] public string pDocName;
[MarshalAs(UnmanagedType.LPStr)] public string pOutputFile;
[MarshalAs(UnmanagedType.LPStr)] public string pDataType;
}
[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi,
ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter,
IntPtr pd);
[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
public static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi,
ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level,
[In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
[DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
public static extern bool EndDocPrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
public static extern bool StartPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
public static extern bool EndPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
public static extern bool WritePrinter(IntPtr hPrinter, byte[] pBytes, Int32 dwCount, out Int32 dwWritten);
// SendBytesToPrinter()
// When the function is given a printer name and an unmanaged array
// of bytes, the function sends those bytes to the print queue.
// Returns true on success, false on failure.
public static bool SendBytesToPrinter(string szPrinterName, byte[] pBytes, Int32 dwCount)
{
Int32 dwError = 0, dwWritten = 0;
IntPtr hPrinter = new IntPtr(0);
DOCINFOA di = new DOCINFOA();
bool bSuccess = false; // Assume failure unless you specifically succeed.
di.pDocName = "Zebra Label";
di.pDataType = "RAW";
// Open the printer.
if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
{
// Start a document.
if (StartDocPrinter(hPrinter, 1, di))
{
// Start a page.
if (StartPagePrinter(hPrinter))
{
// Write your bytes.
bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
}
// If you did not succeed, GetLastError may give more information
// about why not.
if (bSuccess == false)
{
dwError = Marshal.GetLastWin32Error();
throw new Win32Exception(dwError);
}
return bSuccess;
}
}
I did a lot of work on Zebra ZT230 and GX430t printers last year, and the thing I found out about them was using the ZPL instructions over TCP sockets via port 9100 was a LOT more reliable.
I know this is taking your conversation in a very different direction, but having tried the spool / Win32 approach I can tell you using sockets was a lot more reliable. Let me know if you need some sample code.
Wrote a kiosk application using a KR403 last year. I was able to
successfully print and poll the status of the printer to see if there
was a paper jam low paper etc via usb using the blog post below.
http://danielezanoli.blogspot.com/2010/06/usb-communications-with-zebra-printers.html
Using print spooler (Print only)
https://sharpzebra.codeplex.com/SourceControl/latest#src/Com.SharpZebra/Printing/RawPrinter.cs
I used the ZebraDesigner to do my initial layout. On the print screen
inside the zebra designer there is a print to file option that will
save your design as a txt file with ZPL in it. I then took that file
broke it up into sections and created a helper class that uses a
StringBuilder internally so I could focus on certain pieces of the zpl
since it can be overwhelming to look at more than 1-2 lines.
var kioskTicketBuilder = new KioskTicketBuilder();
kioskTicketBuilder.SetPrinterDefaults();
kioskTicketBuilder.DisplayTicketHeader();
kioskTicketBuilder.DisplayInformationHeading(data.Name, data.todaysDate, data.ClientName, data.ClientCode);
kioskTicketBuilder.DisplayMoreStuff()
kioskTicketBuilder.DisplayBarcode(data.TrackingId);
kioskTicketBuilder.EndOfJob();
return kioskTicketBuilder.GetPrintJobToArray();
Also if you go to the the printer properties > Printing Defaults > Tools
Tab There is an option to send a file of zpl to the printer or send
individual commands. This is really good for testing your zpl seperate
from your application.

Size of addrinfo structure

I want to duplicate addrinfo structure (simply copying all bytes of it) but my changes result in memory corruption in host application when hooking.
My code is simple as:
byte[] addressInfoBytes = new byte[32];
Marshal.Copy(addressInfoAddress, addressInfoBytes, 0, addressInfoBytes.Length);
newAddressInfoAddress = GCHandle.Alloc(addressInfoBytes, GCHandleType.Pinned).AddrOfPinnedObject();
I thought it happens because 32 is not correct size of this structure.
I calculated this number based on this definition on MSDN:
typedef struct addrinfo {
int ai_flags;
int ai_family;
int ai_socktype;
int ai_protocol;
size_t ai_addrlen;
char *ai_canonname;
struct sockaddr *ai_addr;
struct addrinfo *ai_next;
} ADDRINFOA, *PADDRINFOA;
Do you have any Idea about correct size of this structure and what I do incorrect?
Thank you very much for your time.
I solved this problem long time ago, so I just thought posting it here may help some one else as well.
using System.Net;
using System.Net.Sockets;
[StructLayout(LayoutKind.Sequential)]
internal struct AddressInfo
{
internal AddressInfoHints Flags;
internal AddressFamily Family;
internal SocketType SocketType;
internal ProtocolFamily Protocol;
internal int AddressLen;
internal IntPtr CanonName; // sbyte Array
internal IntPtr Address; // byte Array
internal IntPtr Next; // Next Element In AddressInfo Array
[Flags]
internal enum AddressInfoHints
{
None = 0,
Passive = 0x01,
Canonname = 0x02,
Numerichost = 0x04,
All = 0x0100,
Addrconfig = 0x0400,
V4Mapped = 0x0800,
NonAuthoritative = 0x04000,
Secure = 0x08000,
ReturnPreferredNames = 0x010000,
Fqdn = 0x00020000,
Fileserver = 0x00040000,
}
}
AddressInfo addressInfo = (AddressInfo)Marshal.PtrToStructure(handle, typeof(AddressInfo));

Readprocessmemory into string

I know everything about process and what address i want to read, but i don't know how to use Readprocessmemory function. Do i need to add some usings or something?
I made this in C++, but how can i do it in C#?
char* ReadMemoryText(DWORD address,int size)
{
char ret[size];
DWORD processId;
HWND hwnd = FindWindow("WindowX",NULL);
if(tibia!=NULL)
{
GetWindowThreadProcessId(hwnd,&processId);
HANDLE phandle = OpenProcess(PROCESS_VM_READ, 0, processId);
if(!phandle)
{
cout<<GetLastError()<<endl;
cout <<"Could not get handle!\n";
cin.get();
}
ReadProcessMemory(phandle, (LPVOID)address, &ret,size,0);
char * rt = ret;
for(int i=0;i<size && ret[i]!=0;++i)
cout << ret[i];
return rt;
}
return NULL;
}
Here is an example of using C# that reads a char array from memory. In this case it's the local player's name string from Assault Cube.
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool ReadProcessMemory(
IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, Int32 nSize, out IntPtr lpNumberOfBytesRead);
var nameAddr = ghapi.FindDMAAddy(hProc, (IntPtr)(modBase2 + 0x10f4f4), new int[] { 0x225 });
byte[] name = new byte[16];
ghapi.ReadProcessMemory(hProc, nameAddr, name, 16, out _);
Console.WriteLine(Encoding.Default.GetString(name));
We use pinvoke to get access to ReadProcessMemory exported from kernel32.dll
We use FindDMAAddy to get the address of the name variable. The char array is a fixed size of 16 bytes.
We use ReadProcessMemory using source and destination variables, size 16 and the last argument we just use "out _" because we don't care about bytesRead argument.
Then we need to convert that char array to a string type with proper encoding for which we use Encoding.Default.GetString().
Then write that line to the console.

Categories