Fun with MD5 and Random

Tagged:  •  

GNU Smalltalk comes with a few fairly nice libraries if you want to generate alphanumeric passwords or salts, and compute MD5 digests, both fairly standard things you might want to do when dealing with storing sensitive data such as passwords.

You can generate some random strings fairly easily using built-in libraries without requiring any packages:

| d i l s |
  i := 20.
  d := '0123456789abcdefghijklmnopqrstuvwxyz'.
  l := d size.
  s := String new: i.
  1 to: i do: [ :x |
    s at: x put: (d at: (Random between: 1 and: l))
  ].
  s printNl!

The output of this "program" listing is a string of length 20 from the given "dictionary" (0123...). Some examples are garbled nonsense such as 't3wxjz3jm0lt8pkj4yrn', 'h32qjov8o3u4ry7zermc', and 'stdn4h4wmsg7kzw8j22z'.

To make this a bit more useful, you could create a file 'RandomString.st' and store within it:

Object subclass: #RandomString
  instanceVariableNames: ''
  classVariableNames: ''
  poolDictionaries: ''
  category: ''!

RandomString class methodsFor: 'utility methods'!

from: aDictionaryString size: aSize
  | s l |
  l := aDictionaryString size.
  s := String new: aSize.
  1 to: aSize do: [ :i |
    s at: i put: (aDictionaryString at: (Random between: 1 and: l))
  ].
  ^s!
!

And to use this class later, say from gst:

st> FileStream fileIn: 'RandomString.st'!
FileStream
st> RandomString from: 'abcdefghijklmnopqrstuvwxyz' size: 10!
'dvjxxlheui'
st> RandomString from: 'abcdefghijklmnopqrstuvwxyz' size: 10!
'fuhysygvpl'
st> RandomString from: 'abcdefghijklmnopqrstuvwxyz' size: 10!
'ynbkpunilc'
st> RandomString from: 'abcdefghijklmnopqrstuvwxyz' size: 20!
'mjigpuhdecdcvuinjtqv'

You can build on your 'RandomString' library by providing other features, such as default dictionaries, etc.

To compute the MD5 digest of a string, you simply import the (supplied) package and send the "MD5" object a message. There are of course more possible messages and usages, for example certain messages result in byte arrays instead of a string, but generally what you want is something compatible with the output from a typical MD5 program:

$ echo -n "foo" | md5
acbd18db4cc2f85cedef654fccc4a4d8

There is exactly such a compatible message:

$ gst
st> PackageLoader fileInPackage: 'MD5'!
Loading package MD5
PackageLoader
st> MD5 hexDigestOf: 'foo'!
'acbd18db4cc2f85cedef654fccc4a4d8'

Combining these two snippets can help you solve the following use cases:

1. Generate a random alphanumeric password
2. Generate a random salt
3. Compute the MD5 digest for a given string for storage

Good luck, and happy typing, you Smalltalkers who can type.

For the record, in 2.95 the module is named Digest (MD5 is still available for backwards compatibility) and support SHA1 too.

User login