Cryptography Code
This page contains various articles on cryptography and useful free cryptographic software code that David Ireland has written or adapted. This page is updated frequently, so keep checking.
Contents
Recommended reading
 Cryptography: Theory and Practice by Douglas R. Stinson.
 Cryptography Engineering by Niels Ferguson, Bruce Schneier and T. Kohno.
 Security Engineering by Ross J. Anderson.
 Cryptography and Network Security by William Stallings
Articles and Code  Base64 encoding in Visual Basic  bdcalc: a calculator for large natural numbers  BigDigits: Multipleprecision 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  CrossPlatform Encryption  Cube root constants in SHA512  Cyclic Redundancy Code algorithms CRC32, CRC16 and CRC24 in VB6  CRT  Encoding is Not Encryption  Encrypting variablelength strings with a password  Encryption with International character sets  Euclidean Algorithm  FergusonSchneier RSA Encryption  Freeware utilities to generate and check MD5, SHA1 and CRC32 checksums  Links  MD5 in Visual Basic  Modular arithmetic freeware  MySecret  a freeware commandline encryption utility using Blowfish  Portugal DGCI Billing Software Certification  Public key cryptography using discrete logarithms  RSA algorithm notes and advice on its use and its theory  RSA and DiffieHellman in Visual Basic  Test vectors for SHA1, SHA2 and SHA3  SHA256 test vectors  Storing and representing ciphertext  Test Vectors for RSAKEM  Unix crypt(3) password encryption program  Using byte arrays in VB6  Using keys in cryptography: a brief introduction to keys and passwords  Using padding in cryptography  XMLDsig ◊
Articles and Code
Test vectors for SHA1, SHA2 and SHA3
This page summarises useful test vectors for the secure hash algorithms SHA1, SHA2 and the new SHA3 (Kaccak, announced the winner of the SHA3 competition by NIST in October 2012). Updated for FIPS202 August 2014 ...read more...
Public key cryptography using discrete logarithms
[20130825] A series of pages that look at public key cryptography using the properties of discrete logarithms ...read more...
Cube root constants in SHA512
Ever wondered how to compute the constants in the SHA512 specification FIPS PUB 1804? OK, probably not. These are the first 64 bits of the fractional parts of the cube roots of the first 80 prime numbers. Includes source code in C ...read more...
Encrypting credit card numbers using Feistel Finite Set Encryption Mode (FFSEM)
Suppose we want to store a credit card number in encrypted form in a database, but we are only allowed to store it in the same format as another credit card number ...read more...
Signing an XML document using XMLDsig (Part 1)
[20120511] This page demonstrates how to create a digital signature in XML. This is a simple [sic] example of an enveloping signature where we sign a straightforward text string inside an XML document. ...read more...
Signing an XML document using XMLDsig (Part 2)
[20120511] On this page we look at how to create an enveloped signature of an XML document using XMLDSIG. ...read more...
Portugal DGCI Billing Software Certification
[20100807] We look at the new Billing Software Certification (Certificação de Software Facturação) scheme introduced by the Portugal General Directorate of Taxes (Direcção Geral dos Impostos) (DGCI) in June 2010. We point out the problems that are guaranteed to arise in using the OpenSSL software in the manner suggested, as well as apparent errors in the test vectors provided. ...read more...
XMLDsig and the Chile SII
[20090127] Using XMLDsig to create and verify electronic invoices for the Servicio de Impuestos Internos (SII) of Chile ...read more...
RSA and DiffieHellman in Visual Basic
It is possible to do RSA calculations in VB6/VBA. This code carries out modular exponentiation on arbitrarylarge integers ...read more...
MD5 Message Digest Algorithm in Visual Basic
MD5 creates a 16byte (128bit) oneway 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 variablelength 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 CRC32, CRC16 and CRC24
Cyclic Redundancy Code (CRC) algorithms CRC32, CRC16 and CRC24 have been written in VB6 ...read more...
Freeware utilities to generate and check MD5, SHA1 and CRC32 checksums
Download this set of three freeware commandline utilities that generate or check MD5, SHA1 and CRC32 checksums for a file or list of files ...read more...
RSA Theory
The RSA Theory page looks at the mathematics behind the RSA algorithm with mathematical proofs of how it works. Completely rewritten November 2011. ...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. ...read more...
The Euclidean Algorithm and the Extended Euclidean Algorithm
[20100814] People reading our RSA Algorithm page frequently ask about the extended Euclidean algorithm. We look at how to use it, solve typical exam questions and show how to do the calculations by hand ...read more...
Using the CRT with RSA
[20110219] We look at how the Chinese Remainder Theorem (CRT) can be used to speed up the calculations for the RSA algorithm ...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 commandline 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...
FergusonSchneier RSA Encryption
This page gives example code in Visual Basic (VB6 and VB.NET/VB200x) using CryptoSys PKI to do RSA encryption in the manner suggested by Ferguson and Schneier in their book Practical Cryptography (Wiley, 2003) ...read more...
Test vectors for RSAKEM
Some test vectors for the RSAKEM algorithm (now out of date but still the only ones we've seen) ...read more...
Key Derivation Functions: How many KDFs are there?
[20080614] A key derivation function (KDF) is a deterministic algorithm to derive a key of a given size from some secret value ...read more...
CrossPlatform 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...
Encryption with International Character Sets
If you are having problems doing cryptography with international character sets, you need to understand just one thing ...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 8bit binary data in a 7bit printable form that can be safely transferred through the Internet. Here is how to do it in VB6 ...read more...
BigDigits multipleprecision arithmetic library in ANSI C
BigDigits is a library of multipleprecision arithmetic routines written in ANSI C to carry out the usual large natural number calculations required in cryptography calculations ...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...
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, and to my son, Robert Ireland for all his tennis tricks.
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 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 most recent revisions 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.
If you want a version in ASP/VBScript, see Blowfish in ASP below.
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 32bit 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 Cryptography with International Character Sets.
Q. Why can't I use your program to decrypt something encrypted by Product X? See CrossPlatform Encryption.
Q. Do you have a version in VB.NET? No.
Blowfish in ASP/VBScript
Blowfish in ASP has a conversion of the Blowfish Visual Basic code into VBScript and a sample demo ASP page by Hart Penn.
This is an Apache web site on a Unix server so we can't put up the ASP demo but the 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.
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" Pbox 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.
MySecret.exe  a commandline encryption utility
MySecret.exe is a commandline 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 base64 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.
BigDigits multipleprecision arithmetic library in ANSI C
BigDigits is a library of multipleprecision arithmetic routines written in ANSI C to carry out the usual large natural number calculations required in cryptography calculations.
This library includes the classical multipleprecision 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 RabinMiller Probabilistic Primality Test procedure from FIPS186 to show that a large integer is probably prime. The test functions include examples using the RSA algorithm in both multipleprecision and singleprecision 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 notparticularlyrestrictive 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 IfThis 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.
htpasswd algorithm with SHA1 and salted SHA1: If you need to create and verify passwords using the Apache `htpasswd' algorithm with SHA1 or salted SHA1, see Using htpasswd passwords with CryptoSys API.
RSA and DiffieHellman 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 4 February 2009.
Thanks to Philippe Bonnardel for pointing out a problem in the text comparisons in mpFromHex,
and thanks to "Mark" for the fix with the "0" in mpModExp.
There are examples of how this can be used to carry out RSA encryption and simple DiffieHellman 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 miniRSA encryption of the message 0x35b9a3cb with 32bit 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 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 8bit binary data in a 7bit 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 ContentTransferEncoding 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 AZ, az, 09 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 (VB6/VBA), download basRadix64.txt 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: The early 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 32bit 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.
SHA256 Test Vectors
We wrote our own implementation of the SHA256 hash algorithm as described in FIPS 180 Secure Hash Standard. This is incorporated into our CryptoSys API and CryptoSys PKI products. 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 SHA256 (and SHA384 and SHA512) on his site as well as opensource 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 32bit 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 6
MD5 creates a 16byte (128bit) oneway 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 oneway 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 (zipped 6 kB).
(VBA users should delete the first line with Attribute VB_Name
in it.)
This code is relatively slow.
VB6 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. Updated 20101020 to fix issue with ">" vs ">=" in uwAdd.
Thanks to Loek for pointing this out.
For speed, use the MD5 functions in our
CryptoSys API library.
which comes with the MD5, SHA1, SHA224, SHA256, SHA384, SHA512, the new SHA3 algorithms (and their HMAC cousins)
and lets you provide the message data input
as either a String
, Byte
array, or as a file.
Cyclic Redundancy Code algorithms CRC32, CRC16 and CRC24 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 oneway ones). The CRC32, CRC16 and CRC24 algorithms have been written in Visual Basic together with a CRC32 function for files. You can download them all as a Zipped File (10 kB). Please read the Readme document.
The CRC32 algorithm is the one specified in ISO 3309 and ITUT V.42 and used by WinZip. It uses the polynomial 0x04C11DB7. The CRC16 algorithm uses the polynomial 0x8005. The CRC24 algorithm is described in RFC 2440 OpenPGP Message Format. Our CRC24 algorithm is slower than the CRC32 and CRC16 versions because it does not use a lookup table, but the code is simpler. The CRC32 and CRC16 algorithms in VB6 were first posted on 6 May 2001 and the CRC24 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.
CRC32 without using a lookup table
28 October 2006: We needed a version of CRC32 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 CRC32 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, SHA1 and CRC32 checksums
md5sum.exe, sha1sum.exe and crc32sum.exe are freeware commandline programs that generate or check MD5, SHA1 and CRC32 checksums for a file or list of files. Download this set of three freeware commandline 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 *1239.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 *1239.txt 352441c2 *abc.txt 0d4a1185 *hello.txt 38e6c41a *hellon.txt >sha1sum *.txt f7c3bc1d808e04732adf679965ccc34ca7ae3441 *1239.txt a9993e364706816aba3e25717850c26c9cd0d89d *abc.txt 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed *hello.txt 88a5b867c3d110207786e66523cd1e4a484da697 *hellon.txt
Binary and byte operations in Visual Basic 6
Doing cryptographic operations in Visual Basic is tricky because VB6 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 VB6. 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:
FFFFFFFFThe 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 backandforth between
String
types
and Byte
arrays, use the standard (but not wellknown) 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
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
(20080625).
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 32bit 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 6 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 CrossPlatform 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 variablelength 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 variablelength strings with a password article includes an explanation of the methods and the full source code. (Last updated June 2009).
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 page on RSA Theory (completely rewritten November 2011). To help with your RSA calculations, we have some freeware programs to carry out modular arithmetic calculations from the command prompt (last updated 111111). We've also written some VB6/VBA code to carry out the basic RSA computation, which you might find helpful.
Commercial Products
We sell commercial cryptography software under the CryptoSys brand name. You can download fullyfunctional trial versions to try them out at no cost.CryptoSys API: CryptoSys API is library of cryptography tools that includes the standard symmetrical encryption functions (AES, Triple DES, Blowfish, DES), hash functions (MD5, SHA1, SHA2, SHA3), HMAC and CMAC authentication, and other cryptographic utilities. More details....
CryptoSys PKI Toolkit: The CryptoSys PKI Toolkit provides RSA public key encryption and digital signatures, X.509 certificate creation and management, and lets you create and read cryptographic message syntax (CMS/PKCS#7) envelopedData and signedData objects that can be used with S/MIME. More details....
To understand the differences between the above two CryptoSys products, please compare their features.
FirmaSAT: FirmaSAT is a standalone product which enables you to create and read CFD and CFDi digital tax receipts (Comprobantes Fiscal Digital) as specified by the Servicio de Administración Tributaria (SAT) in Mexico.
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. 
A Few Thoughts on Cryptographic Engineering  The blog of Matthew Green, a cryptographer and research professor at John Hopkins University. 
Peter Gutmann's page  Information on cryptography and PKI matters from a leading expert in the field with a good sense of humour. Check out his DumpASN1 C program to read BERencoded ASN.1 files, his style guide to writing X.509 certificates, and his rant on the M*soft inspired PFX/PKCS12 standard. 
Neal R. Wagner  The Laws of Cryptography: a series of wellexplained 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 wellwritten 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.
The entire first edition (2001) and some chapters from the second edition (2008) are now
available on his site.
One of the interesting facts from the second edition is that the most commonlyused password
has changed in recent years from password to password1 .

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. 
Worst hotel in the world  OK, not cryptography but a warning about the worst hotel in the world: the Norwood Hotel in Accrington, England. 
Feedback
To comment on this page or ask a question, please send us a message.
This page last updated 19 October 2014