1 /*******************************************************************************
2 
3     libgcrypt with algorithm 3DES and mode CFB
4 
5     Requires linking with libgcrypt:
6             -L-lgcrypt
7 
8     See_Also:
9         https://en.wikipedia.org/wiki/Triple_DES
10         https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
11 
12     Copyright:
13         Copyright (c) 2009-2016 dunnhumby Germany GmbH.
14         All rights reserved.
15 
16     License:
17         Boost Software License Version 1.0. See LICENSE_BOOST.txt for details.
18         Alternatively, this file may be distributed under the terms of the Tango
19         3-Clause BSD License (see LICENSE_BSD.txt for details).
20 
21         Bear in mind this module provides bindings to an external library that
22         has its own license, which might be more restrictive. Please check the
23         external library license to see which conditions apply for linking.
24 
25 *******************************************************************************/
26 
27 module ocean.util.cipher.gcrypt.TripleDES;
28 
29 import ocean.util.cipher.gcrypt.core.Gcrypt;
30 
31 /*******************************************************************************
32 
33     Gcrypt with 3DES with mode CFB.
34 
35     See usage example in unittest below.
36 
37 *******************************************************************************/
38 
39 public alias GcryptWithIV!(Algorithm.GCRY_CIPHER_3DES, Mode.GCRY_CIPHER_MODE_CFB) TripleDES;
40 
41 version (unittest)
42 {
43     import ocean.core.Test;
44     import ocean.meta.types.Qualifiers;
45 }
46 
47 /// Usage example
48 unittest
49 {
50     // TripleDES requires a key of length 24 bytes
51     auto key = cast(immutable(ubyte)[])"a key of 24 bytesa key o";
52     // TripleDES requires an initialisation vector of length 8 bytes.
53     auto iv = cast(immutable(ubyte)[])"iv8bytes";
54 
55     istring text = "This is a text we are going to encrypt";
56     mstring encrypted_text, decrypted_text;
57 
58     // Create the class
59     auto two = new TripleDES(key);
60 
61     // encryption/decryption is done in place so first copy the plain text to a
62     // buffer.
63     encrypted_text ~= text;
64 
65     // The actual encryption.
66     two.encrypt(encrypted_text, iv);
67 
68     // Since decryption is done in place we copy the decrypted string to a new
69     // buffer.
70     decrypted_text ~= encrypted_text;
71 
72     // The decryption call
73     two.decrypt(decrypted_text, iv);
74 
75     // We have now successfully encrypted and decrypted a string.
76     test!("==")(text, decrypted_text);
77 }
78 
79 
80 // Test that only 24-bytes keys are allowed
81 unittest
82 {
83     auto key = cast(immutable(ubyte)[])"a key of 24 bytesa key o";
84     TripleDES.testFixedKeyLength(key);
85 }