Dan Griffin's Blog

Comments on security, PKI, smart cards, cryptography, and entrepreneurship.

I stumbled across a bug in a couple of the .NET P/Invoke wrapper classes that I wrote for the (native/win32) Windows Smart Card API for this MSDN article.

To understand the bug, take a look at this article on P/Invoke. Scroll down to the bottom and click on Figure 3 to expand it (otherwise IE wont be able to find some of the search terms you might want to use to jump directly to it - lame).

As an aside, the smart card API is one of the most challenging Ive seen for writing .NET wrapper classes, because it has multiple layers of embedded structures, each with input and output parameters, and a mix of ANSI and Unicode strings. Fun!

Anyway, the mistake I made is in handling output string parameters. As Fig 3 in the second article above shows, you need to use the System.Text.StringBuilder class for that since it gives you a read-write array. In contrast, the string type, which is what I used in a couple of places, is read-only.

The result of such a bug can be a little frustrating to diagnose, since the underlying API doesnt fail. Instead, what you receive back in managed code is an unmodified string. Be sure to test P/Invoke interfaces carefully to catch problems such as this.

Permalink |

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment