GcryptWithIV.generateIV

Helper function to generate a void[] suitable for use as an IV in unittests.

class GcryptWithIV(Algorithm algorithm, Mode mode)
version(unittest)
static
void[]
generateIV
()

Return Value

Type: void[]

void[] of the correct length for an IV

Examples

Test that only initialisation vectors of the correct length are acceptable.

auto key = generateKey();
auto iv = generateIV();

auto crypt = new typeof(this)(key);

auto buf = generateMessage();

// Too short should fail
testThrown!(GcryptException)(crypt.encrypt(buf, iv[0 .. $-1]));

// Too long should fail
iv.length = iv.length + 1;
testThrown!(GcryptException)(crypt.encrypt(buf, iv));
iv.length = iv.length - 1;

// The correct length should succeed
crypt.encrypt(buf, iv);

Test encrypting and decrypting a short value.

auto key = generateKey();
auto iv = generateIV();

auto crypt = new typeof(this)(key);

auto original = generateMessage();
mstring buf;
buf ~= original;

// Encrypt buf in place
crypt.encrypt(buf, iv);
test!("!=")(buf, original);

// Decrypt buf in place
crypt.decrypt(buf, iv);
test!("==")(buf, original);

Test that setting an IV does affect the outcome of encryption.

auto key = generateKey();

auto crypt = new typeof(this)(key);

auto original = generateMessage();
mstring buf;
buf ~= original;

// Encrypt buf in place
auto iv = generateIV();
crypt.encrypt(buf, iv);

// Encrypt with a different IV and test that is not the same as before
mstring buf2;
buf2 ~= original;
auto iv2 = generateIV();
foreach ( ref b; cast(ubyte[])iv2 )
{
    b++;
}
crypt.encrypt(buf2, iv2);

test!("!=")(buf, buf2);

Meta