Cryptography Code
About the cryptography code page
This page contains useful free cryptographic software code that David Ireland has written or adapted in Visual Basic and ANSI C. This page is updated frequently, so keep checking. (This page last updated 25 June 2008.) Table of contents below. Quick site map:-
Articles and Code | Contents | Links | Blowfish in VB | MySecret | BigDigits | RSA |
Products
We also sell commercial cryptographic products. They probably do things better than the free code available on this page. Free trial versions are available so you can try them out.CryptoSys API: CryptoSys API is library of cryptography tools that includes the standard symmetrical encryption functions (AES, Triple DES, Blowfish, DES), secure hash functions (MD5, SHA-1/256/384/512), HMAC and CMAC authentication mechanisms, and other cryptographic utilities. Version 4.0 was released 12 September 2007 with interfaces for VB6, VBA, C, C++, VB.NET/VB200x, C# and ActiveX/COM/ASP programmers, plus a Linux version. More details....
CryptoSys PKI Toolkit:
The CryptoSys PKI Toolkit provides
RSA public key encryption, digital signatures, X.509 certificate handling,
and cryptographic message syntax (CMS/PKCS#7) envelopedData and signedData objects that can be used with S/MIME.
It also now includes RSA-KEM ("Simple RSA").
Version 3.2 was released 2 February 2008 with interfaces for
VB6, VBA, C, C++, VB.NET/VB200x and C# programmers,
plus a Linux version.
More details....
A command-line utility to create
SAT Mexico digital signatures is available:
see the FirmaSAT page.
To understand the differences between our CryptoSys products, please compare their features.
Email Analysis: Not quite cryptography, but please check out our DBXanalyzer program that allows you to read, analyse and export files from Microsoft Outlook Express DBX files and backups. Last upgraded February 2008. For more details, see the DBXanalyzer page.
World Clock: Our free Wclock world time display program was last updated on 1 January 2008
Articles and Code
Key Derivation Functions: How many KDFs are there?
[2008-06-14] A key derivation function (KDF) is a deterministic algorithm to derive a key of a given size from some secret value ...read more...
Encrypting credit card numbers in a database
[2008-05-26] You need to encrypt a set of clients' credit card numbers in a database. Here's how not to do it, followed by some better methods ...read more...
RSA and Diffie-Hellman in Visual Basic
It is possible to do RSA calculations in VB6/VBA. This code carries out modular exponentiation on arbitrary-large integers ...read more...
Crypt3 password encryption function
We occasionally get asked if we have a program that will carry out the old crypt(3) password encryption function used in Unix systems. Yes we do ...read more...
MD5 Message Digest Algorithm in Visual Basic
MD5 creates a 16-byte (128-bit) one-way hash or message digest of a string of any length. You can use it to check passwords or create a signature for a file. This is an implementation of the MD5 algorithm in VB6/VBA ...read more...
Using Padding in Encryption
The most common query we get about cryptography concerns padding with a block cipher. If you have to encrypt some data to send to another user and everything else works OK except the last few bytes, your problem is probably one of padding ...read more...
Using Keys in Cryptography
We get many queries from people about how to use keys in cryptography and how to represent them. This page is a simple introduction. If you take away nothing else, remember that ...read more...
Encrypting variable-length strings with a password: doing it properly
We have put together two example projects (one in VB.NET and one in VB6) that demonstrate how to encrypt data of variable length with a secret password - properly! It includes the full source code ...read more...
Cyclic Redundancy Code algorithms CRC-32, CRC-16 and CRC-24
Cyclic Redundancy Code (CRC) algorithms CRC-32, CRC-16 and CRC-24 have been written in VB6 ...read more...
Freeware utilities to generate and check MD5, SHA-1 and CRC-32 checksums
Download this set of three freeware command-line utilities that generate or check MD5, SHA-1 and CRC-32 checksums for a file or list of files ...read more...
SHA-1 code in C
After a day spent looking for a version of SHA-1 that would work on my Windows machine, I gave up and re-wrote this version ...read more...
Additional test vectors for SHA-256
We think the test with 2^29 (0x20000000) byte repetitions is important ...read more...
Blowfish in Visual Basic
How to do Blowfish in Visual Basic (VB6). This is an original Visual Basic version of Bruce Schneier's Blowfish algorithm ...read more...
MySecret.exe - a command-line encryption utility
MySecret.exe is a freeware utility that enables you to encrypt the contents of the clipboard or disk files. It uses the Blowfish algorithm ...read more...
RSA Algorithm
Our RSA Algorithm Page contains notes and advice on the use of the RSA algorithm with simple examples and notes on its use in practice. See also our Theory and Proof of the RSA Algorithm ...read more...
Encryption with International Character Sets
To understand the principles of encryption with international character sets, it is important first to grasp a fundamental principle about encryption and decryption ...read more...
Cross-Platform Encryption
Can a file encrypted in VB be decrypted by an application written in Java? Why can't I use your program to decrypt something encrypted by Product X? ...read more...
Storing and representing ciphertext
Ciphertext is not text! In cryptography programming you have to be very careful to differentiate between binary data and what we'll refer to here as text data ...read more...
Encoding is Not Encryption
It's unfortunate that the words encryption and encoding tend to get used as synonyms. In cryptography they mean two different things ...read more...
Using Byte Arrays in VB6/VBA
To carry out cryptographic operations in Visual Basic (VB6 and VBA) we should use the unambiguous Byte type instead of the much more convenient String type. This page shows how to handle arrays of the Byte type ....read more...
Binary and byte operations in VB6
Doing cryptographic operations in Visual Basic is tricky because VB6 doesn't have unsigned types (except the Byte type). A simple bit shift operation in C like x <<= 8 is not a simple matter with a Long variable in VB ....read more...
Base64 encoding in Visual Basic
Base64 encoding is used to represent 8-bit binary data in a 7-bit printable form that can be safely transferred through the Internet. Here is how to do it in VB6 ...read more...
BigDigits multiple-precision arithmetic library in ANSI C
BigDigits is a library of multiple-precision arithmetic routines written in ANSI C to carry out the usual large natural number calculations required in cryptography calculations ...read more...
Rules
Our aim here is to make useful software available for developers to use in their applications or research. Unless otherwise noted, all code on this site has been authored by David Ireland of DI Management Services Pty Limited who retains exclusive copyright protection and distribution rights. All efforts have been made to acknowledge the authors of work on which the code is based, where appropriate. Most of the software may be used in your applications without charge. Some software requires a licence for commercial use or distribution. Please refer to the individual copyright notices for the specific details.
The code may only be used as part of an application. You cannot distribute or reproduce any of the files or code found in this site separately by any means without the express written permission of the author.
Acknowledgements
Thanks to all the people who have taken the time to write and suggest changes or improvements to the work on this and associated pages. I've tried to mention the significant contributors in the appropriate places. Thanks too, to my wife, Veenu Ireland, for all her support.
Blowfish: a Visual Basic version
This is an original Visual Basic version of Bruce Schneier's Blowfish algorithm as detailed in "Applied Cryptography", 2nd edition, 1996.
You can download the complete source code and demo projects BlowfishVB_6a.zip (128kB). Please read the terms and conditions for use of this code in BlowfishReadMe.txt. Some test functions are included in basTestBlowfish (included in the main zip file). It has been tested in VB6 and Office VBA. Version 6 released 20 November 2003. Thanks to Robert Garofalo in particular for his advice on speeding it up, and to Doug J Ward and Jim McCusker for their suggestions and advice incorporated here. The Visual Basic version of Blowfish was first published by David Ireland in October 2000.
Michael Coe tells us (2 November 2007) that the VB6 code can be made to work in VB4 by adding the declaration:
Declare Function VarPtr Lib "VB40032.DLL" (variable As Any) As Long
Details of the latest revisions (November 2003) are explained in Blowfish Version 6 Changes. For more details see the Blowfish VB Demo Page or, for a more complicated example showing CBC mode and raw encryption, see the Blowfish Extended VB Demo Page.
Please also read the section on section Binary and byte operations in Visual Basic below. In particular users with systems set up to use full 32-bit Unicode or CJK oriental characters may need to do a global change of the Asc() and Chr() functions used in the Blowfish and basConvert functions to AscW() and ChrW(). Thanks to David Wolf for this tip.
For more information on dealing with Unicode and ANSI characters sets see Encryption with International Character Sets.
Q. Why can't I use your program to decrypt something encrypted by Product X? See Cross-Platform Encryption.
A Blowfish DLL you can call from Visual Basic or C/C++
If the interpreted VB version is too slow or too insecure for you, use the Blowfish functions and methods in our commercial DLL CryptoSys API. It includes API functions that carry out Blowfish encryption operations on byte arrays, hexadecimal strings, base64 strings, and files in ECB, CBC, CFB, OFB and CTR modes. It includes interfaces for programmers in C, C++, C#, VB6, VBA, VBScript, COM and VB.NET. For more details, and to download a free copy for personal use and testing, see the CryptoSys API page.
An example call to encrypt a file might look like:
lngRet = BLF_FileHex("C:\hello.enc", "C:\hello.txt", _
"fedcba9876543210", True, "CFB", "0123456789abcdef")
As an indication of the speed increase over interpreted VB, on a PIII 500 MHz machine it reduced the time taken to encrypt a 2.5 MB test file from over 90 seconds to about 3 seconds!
This example uses base64 strings directly:
Dim sInput As String
Dim sOutput As String
Dim sKey as String
sInput = "NzY1NDMyMSBOb3cgaXMgdGhlIHRpbWUgZm9yIAAAAAA="
sOutput = String(Len(sInput), " ")
sKey = "ASNFZ4mrze/w4dLDtKWWhw=="
lngRet = BLF_B64Mode(sOutput, sInput, sKey, _
True, "CBC", "/ty6mHZUMhA=")
Example of use in a C program:-
#include "diCryptoSys.h"
long result;
char sInputHex[] = "0123456789ABCDEF";
char sKeyHex[] = "FEDCBA9876543210";
char sCorrectHex[] = "0ACEAB0FC6A0A28D";
/* NB Output for Hex requires an extra byte */
char sOutputHex[sizeof(sInputHex)+1];
printf("Testing BLF_Hex()...\n");
result = BLF_Hex(sOutputHex, sInputHex, sKeyHex, 1);
assert (result == 0);
Blowfish in ASP/VBScript
Here is a conversion of the Blowfish Visual Basic code into VBScript and a sample demo ASP page by Hart Penn. Download BlowfishASP.zip (18 kB) (revised 13 Aug 2002).
This is an Apache web site on a Unix server so we can't put up the ASP demo but the Blowfish in ASP page has a screen dump and some hints on how to convert VB to VBScript.
Ironically, all the new work that went into making new basConvert
conversion functions using
dynamic arrays doesn't convert over to VBScript, so we had to go back to the original
basByteUtil functions.
Also, be warned, this demo works for the functions it uses - there may well be some unchecked
bugs elsewhere. (13 Aug 2002) Fixed bug in DecodeStr64 function in basRadix64.asp.
Thanks to James Spibey for pointing this out.
Blowfish in C
Here is Bruce Schneier's code in C for his
Blowfish algorithm.
This version is fully ANSI compliant and contains
the "missing" P-box values omitted from the book.
Try this
test code
.
It contains a test suite by Eric Young and compiles OK
with both VC5++ and with Unix gcc.
This code may be freely distributed.
Updated 29 July 2003: thanks to Mehul Motani for pointing out an error in the test code
for readDataLine().
MySecret.exe - a command-line encryption utility
MySecret.exe is a command-line freeware utility that enables you to encrypt the contents of the clipboard or disk files. It is small - 50 kB - and quick. It uses the Blowfish algorithm to create base-64 encoded text that can be easily transmitted over the Internet. For more information, including the download and the technical details of how it works, see the MySecret Blowfish Encryption Utility page.
MySecret was first published 8 February 2002. Version 3 released 12 May 2007. Thanks to Stefan Neumann for help in fixing a bug in an earlier version and for planting the seed to include a proper check when decrypting. There is a Linux version available for ix86 machines and a demonstration VB6 project using CryptoSys API that shows how the algorithm works.
We use MySecret to pass confidential data to a web site for one of our clients: see the web site of Chancellor Hattersley Lloyd.
BigDigits multiple-precision arithmetic library in ANSI C
BigDigits is a library of multiple-precision arithmetic routines written in ANSI C to carry out the usual large natural number calculations required in cryptography calculations.
This library includes the classical multiple-precision arithmetic algorithms from Knuth: add, subtract, multiply and divide. It also includes modular multiplication, exponentiation and inversion; number theory functions such as greatest common divisor; and the Rabin-Miller Probabilistic Primality Test procedure from FIPS-186 to show that a large integer is probably prime. The test functions include examples using the RSA algorithm in both multiple-precision and single-precision forms, which are excellent tests for the integrity of most of the functions in the library.
Go to the BigDigits page for more details, including a full listing of all the functions included. Download the source code and read the not-particularly-restrictive copyright notice that applies to this library, especially if you want to use it in your own commercial applications. Please check the Errata for changes.
Crypt3 password encryption function
We occasionally get asked if we have a program that will carry out the old crypt(3) password encryption function used in Unix systems. Yes we do. Download our diCrypt3 program (zipped, 26 kB) which you can use with VB6/VBA or in a C program.
To use in a VB6 or VBA program, include the module basCrypt3.bas in your project.
Dim strResult As String
Dim strStoredPwd As String
strResult = Crypt3Wrap("password", "ab")
' This should print abJnggxhB/yWI
Debug.Print strResult
' Try with a random salt
strResult = Crypt3Wrap("password", "")
Debug.Print strResult
' Verify an existing crypt3 result
strStoredPwd = "abJnggxhB/yWI"
strResult = Crypt3Wrap("password", strStoredPwd)
Debug.Print strResult
If strResult = strStoredPwd Then
Debug.Print "Password OK"
Else
Debug.Print "FAILED!"
End If
This should give output like
abJnggxhB/yWI bqtUeFi94GD/c abJnggxhB/yWI Password OK
To use in a C or C++ program, link with diCrypt3.lib.
#include "diCrypt3.h"
#include <stdio.h>
int main(void)
{
char result[14];
long res;
char *correct = "abJnggxhB/yWI";
res = Crypt3(result, "password", "ab");
printf("Crypt3 returns %ld\n", res);
if (res == 0)
{
printf("Result= [%s]\n", result);
printf("Correct=[%s]\n", correct);
}
return 0;
}
In all cases, you must copy the core executable diCrypt3.dll to a directory on your library search path.
You do not register this file, just copy it. Please read the conditions in the readme file before using.
RSA and Diffie-Hellman in Visual Basic
The VB6/VBA code in basModExp.bas contains
a procedure to carry out modular exponentiation.
(Text format (16 kB)
or zipped (6 kB).
(VBA users delete the first line with Attribute VB_Name in it.)
First published 23 September 2005.
Last updated 13 October 2007.
Thanks to Philippe Bonnardel for pointing out a problem in the text comparisons in mpFromHex.
There are examples of how this can be used to carry out RSA encryption and simple Diffie-Hellman key exchange.
The function mpModExp(b, e, m) computes the value of b^e mod m, which is the
core computation you need to perform RSA encryption and Diffie Hellman key exchange.
You pass the parameters as hex strings which can be as long as you like (depending on how long you want to wait :-).
The result is returned in hex format.
strResult = mpModExp("3c", "03", "face")
computes the value of 60^3 mod 64206.
Do a mini-RSA encryption of the message 0x35b9a3cb with 32-bit RSA public key (n, e) = (0x5518f65d, 0x11) and private key d = 0x2309cd31:
' Encrypt c = m^e mod n strResult = mpModExp("35b9a3cb", "11", "5518f65d") Debug.Print strResult & " (expected 528C41E5)" ' Decrypt m' = c^d mod n strResult = mpModExp("528C41E5", "2309cd31", "5518f65d") Debug.Print strResult & " (expected 35B9A3CB)"
Before you ask, no, it doesn't help you generate RSA keys, but you can use existing RSA keys to do RSA encryption and signing, provided you know how to express their values in hex format.
This code is very slow, especially for keys of practical size. It is provided to demonstrate that this computation can be done using just VB6 code. In practice, use our CryptoSys PKI Toolkit, or use the Big Digits code above. For more information on RSA see our page on the RSA Algorithm.
Base64 encoding in Visual Basic
Base64 encoding is used to represent 8-bit binary data in a 7-bit printable form that can be safely transferred through the Internet. It is called radix64 in PGP documents, printable encoding in Privacy Enhanced Mail (RFC1113/RFC1421) and Base64 Content-Transfer-Encoding in the MIME standard (RFC2045). Read an extract from RFC2045 explaining the mechanics.
Binary data encoded with base64 encoding looks like/ty6mHZUMhA=which represents the 8 bytes
FE DC BA 98 76 54 32 10
A base64 string consists of the 64 characters A-Z, a-z, 0-9 and '/' and '+', and can be terminated by up to two '=' characters for padding. Each 4 base64 characters represent 3 bytes. A valid base64 string will always be an exact multiple of 4 characters long.
For our code to do this in Visual Basic, download basRadix64.txt (Version 6 with new functions and error handling, 20 November 2003) and some test functions. These base64 functions are now included in the Blowfish VB demo above and there is an VBScript/ASP version in Blowfish ASP. Many thanks to Chris Thompson for his suggestions and for other advice on improvements. and to Seth Perelman for pointing out a bug in Version 3 of DecodeStr64.
New functions added August 2003: The first versions of our base64 functions used Visual Basic 'String' types to store both the final base64 string and the binary data to be encoded. Binary data should not be stored in the VB 'String' type. It will work OK on a system set up for ANSI, but may have problems on one set up oriental CJK or full 32-bit Unicode character sets.
The two new functions that 'do it properly' are:
EncodeBytes64(abBytes() As Byte) As String DecodeBytes64(sEncoded As String) As VariantThe EncodeBytes64() function expects its input as an array of 'Bytes' and returns a 'String' of base64 characters. The DecodeBytes64() function expects its input to be a String but returns an array of Bytes. For more details on converting between Visual Basic String and Byte types, see Binary and byte operations in Visual Basic.
Super fast encoding (2 Sep 2002):
Carry out extremely fast base64 encoding and decoding plus hexadecimal
encoding and CRC-32 checksum calculations with our free
CryptoSys Encode
utility
.
This carries out base64 encoding and decoding about 25 times faster than the times
given above - over 8 millon characters per second.
SHA-1 code in C
After a day spent looking for a version of SHA-1 that would work on my Windows machine, I gave up and re-wrote this version of AM Kuchling's adaptation of Peter Gutmann's code: sha1.c (16kB) (posted 24 November 2000). This code may be freely distributed with due acknowledgement to all its fathers. Note that all the include files are all gathered together in the one document.
This code includes test vectors from the US Department of Commerce/NIST specification of the Secure Hash Standard fip180-1 (40 kB).
Improvement to SHA-1 Code (5 November 2002): here is a subtle improvement to the code and a point worth noting for general security in all cryptography programming with C. It was sent in by Jon Hanna.
In SHA-1 we clear out possibly sensitive data as follows:-
void SHAFinal(BYTE *output, SHA_CTX *shsInfo)
{
/*...*/
/* Zeroise sensitive stuff */
memset((POINTER)shsInfo, 0, sizeof(shsInfo));
}
This is a fairly standard practice. You'll find it everywhere.
The idea being simply to erase any copies of sensitive data that may be left lying around
in memory.
Jon Hanna points out that many optimisers will just skip writing to a memory location that is never read again. Our brave attempts here to erase our sensitive data may be ignored in the interests of speed and we'd probably never know.
One solution is as follows:-
void SHAFinal(BYTE *output, SHA_CTX *shsInfo)
{
volatile UINT4 optdummy;
/*...*/
/* Zeroise sensitive stuff */
memset((POINTER)shsInfo, 0, sizeof(shsInfo));
/* Force optimiser to do last statement by copying
some zeroised data to a volatile variable */
optdummy = shsInfo->countLo;
}
A more generic version is:-
void Zeroise(void *a, int nbytes)
/* Zeroise a and make sure optimiser doesn't ignore it */
{
volatile unsigned char optdummy;
unsigned char *bp = (unsigned char *)a;
memset(a, 0, nbytes);
optdummy = *bp;
}
It's important that you make the dummy variable volatile so the
optimiser can't afford to ignore the earlier memsetstatement.
Thanks for this tip, Jon.
Our CryptoSys API package contains interfaces to the SHA-1 algorithm for Visual Basic, VBA, VB.NET, C/C++ and C# programmers. You can download a free personal version. It also includes interfaces to SHA-256 and MD5.
SHA-256 Test Vectors
We wrote our own a version of the SHA-256 hash algorithm as described in FIPS 180-2. This is incorporated into our CryptoSys API product. Here are some additional test vectors:
Data = One million repetitions of 'a' CDC76E5C 9914FB92 81A1C7E2 84D73E67 F1809A48 A497200E 046D39CC C7112CD0 Data = 2^29 repetitions of 'a' B9045A71 3CAED5DF F3D3B783 E98D1CE5 778D8BC3 31EE4119 D7070723 12AF06A7
These agree with an implementation created by Aaron Gifford who has many more additional vectors of SHA-256 (and SHA-384 and SHA-512) on his site as well as open-source versions of his source code.
We think the test with 2^29 (0x20000000) byte repetitions is important because it makes the bit count "overflow" into the high 32-bit word. That would seem to us to be a critical place where an implementation of any of the Secure Hash Algorithms might fall over.
MD5 Message Digest Algorithm in Visual Basic
MD5 creates a 16-byte (128-bit) one-way hash or message digest of a string of any length. You can use it to check passwords or create a signature for a file. It's called a one-way hash because it's computationally infeasible to find the original message from the digest or to create another message that produces the same result. MD5 is no longer recommended for new applications but it is still found in many applications. The original specification by RSA Labs is in RFC1321.txt.
The code in basMD5.bas contains an implementation
of the MD5 algorithm in VB6/VBA. This is provided in text format: basMD5.bas.txt (17 kB)
or zipped (6 kB).
(VBA users should delete the first line with Attribute VB_Name in it.)
This code is relatively slow.
VB is not the best language to implement this algorithm - we have to use multiplication and
divide operations to do things that can be done with a single machine instruction in other languages.
But it works.
First published 16 September 2005.
For speed, use the MD5 functions in
CryptoSys API
which comes with the SHA-1, SHA-256 and MD5 algorithms (and their HMAC cousins)
and lets you provide the message data input
as either a String, Byte array, or as a file.
CryptoSys API comes with interfaces for VB6/VBA, C/C++,
ActiveX/VBScript,
vb.net and
C#.
Cyclic Redundancy Code algorithms CRC-32, CRC-16 and CRC-24 in Visual Basic
Cyclic Redundancy Codes (CRCs) are not strictly cryptographic algorithms, but come in handy to check if someone's been messing with your work or for generating quick hash digests (but not one-way ones). The CRC-32, CRC-16 and CRC-24 algorithms have been written in Visual Basic together with a CRC-32 function for files. You can download them all as a Zipped File (10 kB). Please read the Readme document.
The CRC-32 algorithm is the one specified in ISO 3309 and ITU-T V.42 and used by WinZip. It uses the polynomial 0x04C11DB7. The CRC-16 algorithm uses the polynomial 0x8005. The CRC-24 algorithm is described in RFC 2440 OpenPGP Message Format. Our CRC-24 algorithm is slower than the CRC-32 and CRC-16 versions because it does not use a lookup table, but the code is simpler. The CRC-32 and CRC-16 algorithms in VB were first posted on 6 May 2001 and the CRC-24 algorithm on 4 June 2003. Last updated 23 October 2006. Thanks to George Wayne for pointing out that using an Integer counter will lead to overflows on modestly long string inputs.
Super fast CRC-32 checksums:
Carry out extremely fast CRC-32 checksum calculations with our
CryptoSys Encode
utility
.
This carries out CRC-32 calculations at a rate of over 18 millon characters per second
(on a PIII 1GHz machine). This is 20 or 30 times faster than you can achieve
using interpreted Visual Basic functions. It's also free!
CRC-32 without using a lookup table
28 October 2006: We recently needed a version of CRC-32 to use in a C program that didn't use a lookup table. We couldn't find a version on the Net, so here is our version in C. This is the same standard CRC-32 from above which gives CRC("123456789")= 0xCBF43926. There's probably a neat trick to eliminate the use of temp.
unsigned long crc_octets(const unsigned char *octets, int len)
{
unsigned long crc = 0xFFFFFFFF;
unsigned long temp;
int j;
while (len--)
{
temp = (unsigned long)((crc & 0xFF) ^ *octets++);
for (j = 0; j < 8; j++)
{
if (temp & 0x1)
temp = (temp >> 1) ^ 0xEDB88320;
else
temp >>= 1;
}
crc = (crc >> 8) ^ temp;
}
return crc ^ 0xFFFFFFFF;
}
Freeware utilities to generate and check MD5, SHA-1 and CRC-32 checksums
md5sum.exe, sha1sum.exe and crc32sum.exe are freeware command-line programs that generate or check MD5, SHA-1 and CRC-32 checksums for a file or list of files. Download this set of three freeware command-line utilities: digsum.zip (71 kB). Note that the default mode is binary. Use the -t option for text mode. For help, use the -h option and see the readme file included with the download.>md5sum *.txt 25f9e794323b453885f5181f1b624d0b *123-9.txt 900150983cd24fb0d6963f7d28e17f72 *abc.txt 5eb63bbbe01eeed093cb22bb8f5acdc3 *hello.txt a0f2a3c1dcd5b1cac71bf0c03f2ff1bd *hellon.txt >md5sum hellon.txt a0f2a3c1dcd5b1cac71bf0c03f2ff1bd *hellon.txt >md5sum -t hellon.txt 6f5902ac237024bdd0c176cb93063dc4 hellon.txt >crc32sum *.txt cbf43926 *123-9.txt 352441c2 *abc.txt 0d4a1185 *hello.txt 38e6c41a *hellon.txt >sha1sum *.txt f7c3bc1d808e04732adf679965ccc34ca7ae3441 *123-9.txt a9993e364706816aba3e25717850c26c9cd0d89d *abc.txt 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed *hello.txt 88a5b867c3d110207786e66523cd1e4a484da697 *hellon.txt
Binary and byte operations in Visual Basic
Doing cryptographic operations in Visual Basic is tricky because VB doesn't have unsigned types (except the Byte type). That da*n sign bit keeps messing things up. A simple operation in C like x<<=8 is not a simple matter with a Long variable in VB. Try this experiment:
Dim lngX As Long
lngX = &HFFFF ' Half a long?
Debug.Print Hex(lngX)
This will "carry over" the sign bit into the high word and print:
FFFFFFFF
The correct way is to append an ampersand (&) to cast it as a proper long:
Dim lngX As Long
lngX = &HFFFF& ' Correct
Debug.Print Hex(lngX)
Likewise, migrating values from string types to bytes and words has its
difficulties.
To convert back-and-forth between String types
and Byte arrays, use the standard (but not well-known) VBA
StrConv function.
Dim i As Long Dim x() As Byte Dim str As String ' Convert string to ANSI byte array x = StrConv("abcdef", vbFromUnicode) For i = 0 To UBound(x) Debug.Print x(i); Next Debug.Print ' Convert back to a string str = StrConv(x(), vbUnicode) Debug.Print strThis should produce the results:
97 98 99 100 101 102 abcdef
Note how the StrConv
function avoids the need to declare the size of the byte array beforehand.
(Thanks to Robert Garofalo for pointing out this useful function).
For more information see Using StrConv with ANSI, DBCS and Unicode character
sets.
If you want to convert to a byte array without the Unicode conversion, do this:
Dim i As Long Dim x() As Byte Dim str As String str = "abcdef" ' Copy string to byte array without Unicode conversion x = str For i = 0 To UBound(x) Debug.Print x(i); Next Debug.Print ' Convert back to a string str = x Debug.Print strThis will produce the result:
97 0 98 0 99 0 100 0 101 0 102 0 abcdefThis time, we get two bytes for each Unicode character. See Microsoft Knowledge Base Article - 187675 HOWTO: Copy a String to a Byte Array Without Unicode Conversion for more details.
VB6/VBA Code
The functions provided here in
basConvert and
basUnsignedWord
(new revised as at 25 June 2008)
can help you manage some of these issues in your code.
Thanks to Ernie Gibbs for pointing out a subtle error in basUnsignedWord.uw_WordAdd (2008-06-25).
The code in basConvert replaces the now superseded
basByteUtils
with better and faster dynamic arrays.
However, the functions in basByteUtils are still useful for ASP and VBScript applications.
The source code to these three files is in binaryutils.vb6.zip (9 kB).
Note: Users with operating systems that are set up to use full 32-bit Unicode OS or oriental CJK characters may need to do a global replace of Asc() and Chr() with AscW() and ChrW() in the basConvert and basByteUtils functions above. Thanks to David Wolf of Intuit Information Technology Solutions for this tip.
For more hints on how to use arrays of the Byte type in Visual Basic compared to the simpler String type, see Using Byte Arrays in Visual Basic.
Encryption with International Character Sets
For more information on dealing with Unicode and ANSI characters sets see Encryption with International Character Sets. For information on how to read a file encrypted on, say, a Java platform, see Cross-Platform Encryption. For more general advice on handling ciphertext, see Ciphertext is not text! Storing and representing ciphertext.
Using padding correctly in cryptography
We get even more queries from people who are having problems either understanding or implementing the correct methods of padding with block encryption functions. Our Using Padding in Cryptography article describes in detail the machanics of padding with examples using common block encryption algorithms like DES, Triple DES, Blowfish and AES. It considers where you should use padding and where you don't need to. For advanced users, it also gives examples of ways to use random padding to improve the security of your encrypted communication.
Encrypting variable-length strings with a password: doing it properly
We have put together two example projects (one in VB.NET and one in VB6) that demonstrate how to encrypt data of variable length with a secret password - properly! Our Encrypting variable-length strings with a password article includes an explanation of the methods and the full source code. (Last updated February 2007).
RSA Algorithm
Our RSA Algorithm Page contains notes and advice on the use of the RSA algorithm with simple examples and notes on its use in practice. See also our Theory and Proof of the RSA Algorithm (also in in PDF format). Updated September 2004. To help with your RSA calculations, here are two of our freeware programs to carry out modular arithmetic calculations from the command prompt. We've also written some (slower) VB6/VBA code to carry out the basic RSA computations, which you might find helpful (First published September 2005).
Cryptography Links
| Cryptography FAQ | Ten parts of the sci.crypt FAQ. Read these before you ask any questions. |
| Bruce Schneier's page | By the author of Applied Crytography: Protocols, Algorithms and Source Code in C, John Wiley, 1996, and the Blowfish Encryption Algorithm. Lots of info, papers, newsletters, a very comprehensive links page, and variants of the Blowfish source code. |
| Peter Gutmann's page | Up-to-date information on cryptography and PKI matters from a leading expert in the field with a good sense of humour. Has probably the definitive cryptography link farm. Check out his DumpASN1 C program to read BER-encoded ASN.1 files, his style guide to writing X.509 certificates, and his rant on the M*soft inspired PFX/PKCS-12 standard. |
| Neal R. Wagner | The Laws of Cryptography: a series of well-explained and informative pages on cryptography and coding and information theory by Neal Wagner, a professor at University of Texas at San Antonio. Includes a lot of Java code. |
| Snake Oil Warning Signs | Avoiding bogus encryption products: Snake Oil FAQ. "Encryption Software to Avoid" by Matt Curtin. |
| The Six Dumbest Ideas in Computer Security | Marcus Ranum's introduction to the six dumbest ideas in computer security. |
| Ross Anderson | An excellent and well-written site on cryptography issues by the Reader in Security Engineering at the University Of Cambridge. Check out his book Security Engineering: A Guide to Building Dependable Distributed Systems, John Wiley, 2001. The entire book is now available on his site. |
| Digital Timestamping Service | Matthew Richardson's PGP Digital Timestamping Service will timestamp an email sent to it so you can prove your document existed at a given time. Includes a proof of posting service. Operates in clear, header, text, pgp and binary modes. Dates are old, but it still works. |
| RSA Lab's Public Key Cryptography Standards | RSA Labs specifications on public key cryptography (the PKCS standards) and other useful stuff. |
| SUNET crypto archive | A downloadable index of cryptography tools on the SUNET archive, especially for privacy of electronic mail. |
Contents
Base64 encoding in Visual Basic | BigDigits: Multiple-precision arithmetic algorithms source code in ANSI C | Binary and byte operations in Visual Basic | Blowfish in ASP/VBScript | Blowfish in C - including the missing P boxes | Blowfish: a Visual Basic version | Cross-Platform Encryption | Cyclic Redundancy Code algorithms CRC-32, CRC-16 and CRC-24 in VB6 | Encoding is Not Encryption | Encrypting credit card numbers in a database | Encrypting variable-length strings with a password | Encryption with International character sets | Freeware utilities to generate and check MD5, SHA-1 and CRC-32 checksums | MD5 in Visual Basic | MySecret - a freeware command-line encryption utility using Blowfish | RSA algorithm notes and advice on its use and its theory | RSA and Diffie-Hellman in Visual Basic | SHA-1 code in C | SHA-256 test vectors | Storing and representing ciphertext | Unix crypt(3) password encryption program | Using Byte Arrays in Visual Basic | Using keys in cryptography: a brief introduction to keys and passwords | Using padding in cryptography ◊
Feedback
Feedback or questions: Contact Us. Public keys: PGP Keys. Return to Tips and Tutorials Page.
