Welcome to mirror list, hosted at ThFree Co, Russian Federation.

DESExample.java « examples « crypto « bouncycastle « org « java « main « src « core - gitlab.com/quite/humla-spongycastle.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 90a21def94cc70c33f5a280ec07c26527604d06b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package org.bouncycastle.crypto.examples;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.SecureRandom;

import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.KeyGenerationParameters;
import org.bouncycastle.crypto.engines.DESedeEngine;
import org.bouncycastle.crypto.generators.DESedeKeyGenerator;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.DESedeParameters;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Hex;

/**
 * DESExample is a simple DES based encryptor/decryptor.
 * <p>
 * The program is command line driven, with the input
 * and output files specified on the command line.
 * <pre>
 * java org.bouncycastle.crypto.examples.DESExample infile outfile [keyfile]
 * </pre>
 * A new key is generated for each encryption, if key is not specified,
 * then the example will assume encryption is required, and as output
 * create deskey.dat in the current directory.  This key is a hex
 * encoded byte-stream that is used for the decryption.  The output
 * file is Hex encoded, 60 characters wide text file.
 * <p>
 * When encrypting;
 * <ul>
 *  <li>the infile is expected to be a byte stream (text or binary)
 *  <li>there is no keyfile specified on the input line
 * </ul>
 * <p>
 * When decrypting;
 * <ul>
 *  <li>the infile is expected to be the 60 character wide base64 
 *    encoded file
 *  <li>the keyfile is expected to be a base64 encoded file
 * </ul>
 * <p>
 * This example shows how to use the light-weight API, DES and
 * the filesystem for message encryption and decryption.
 *
 */
public class DESExample extends Object
{
    // Encrypting or decrypting ?
    private boolean encrypt = true;

    // To hold the initialised DESede cipher
    private PaddedBufferedBlockCipher cipher = null;

    // The input stream of bytes to be processed for encryption
    private BufferedInputStream in = null;

    // The output stream of bytes to be procssed
    private BufferedOutputStream out = null;

    // The key
    private byte[] key = null;

    /*
     * start the application
     */
    public static void main(String[] args)
    {
        boolean encrypt = true;
        String infile = null;
        String outfile = null;
        String keyfile = null;

        if (args.length < 2)
        {
            DESExample de = new DESExample();
            System.err.println("Usage: java "+de.getClass().getName()+
                                " infile outfile [keyfile]");
            System.exit(1);
        }

        keyfile = "deskey.dat";
        infile = args[0];
        outfile = args[1];

        if (args.length > 2)
        {
            encrypt = false;
            keyfile = args[2];
        }

        DESExample de = new DESExample(infile, outfile, keyfile, encrypt);
        de.process();
    }

    // Default constructor, used for the usage message
    public DESExample()
    {
    }

    /*
     * Constructor, that takes the arguments appropriate for
     * processing the command line directives.
     */
    public DESExample(
                String infile,
                String outfile,
                String keyfile,
                boolean encrypt)
    {
        /* 
         * First, determine that infile & keyfile exist as appropriate.
         *
         * This will also create the BufferedInputStream as required
         * for reading the input file.  All input files are treated
         * as if they are binary, even if they contain text, it's the
         * bytes that are encrypted.
         */
        this.encrypt = encrypt;
        try
        {
            in = new BufferedInputStream(new FileInputStream(infile));
        }
        catch (FileNotFoundException fnf)
        {
            System.err.println("Input file not found ["+infile+"]");
            System.exit(1);
        }

        try
        {
            out = new BufferedOutputStream(new FileOutputStream(outfile));
        }
        catch (IOException fnf)
        {
            System.err.println("Output file not created ["+outfile+"]");
            System.exit(1);
        }

        if (encrypt)
        {
            try
            {
                /*
                 * The process of creating a new key requires a 
                 * number of steps.
                 *
                 * First, create the parameters for the key generator
                 * which are a secure random number generator, and
                 * the length of the key (in bits).
                 */
                SecureRandom sr = null;
                try
                {
                    sr = new SecureRandom();
                    /*
                     * This following call to setSeed() makes the
                     * initialisation of the SecureRandom object
                     * _very_ fast, but not secure AT ALL.  
                     *
                     * Remove the line, recreate the class file and 
                     * then run DESExample again to see the difference.
                     *
                     * The initialisation of a SecureRandom object
                     * can take 5 or more seconds depending on the
                     * CPU that the program is running on.  That can
                     * be annoying during unit testing.
                     *     -- jon
                     */
                    sr.setSeed("www.bouncycastle.org".getBytes());
                }
                catch (Exception nsa)
                {
                    System.err.println("Hmmm, no SHA1PRNG, you need the "+
                                        "Sun implementation");
                    System.exit(1);
                }
                KeyGenerationParameters kgp = new KeyGenerationParameters(
                                    sr, 
                                    DESedeParameters.DES_EDE_KEY_LENGTH*8);

                /*
                 * Second, initialise the key generator with the parameters
                 */
                DESedeKeyGenerator kg = new DESedeKeyGenerator();
                kg.init(kgp);

                /*
                 * Third, and finally, generate the key
                 */
                key = kg.generateKey();

                /*
                 * We can now output the key to the file, but first
                 * hex encode the key so that we can have a look
                 * at it with a text editor if we so desire
                 */
                BufferedOutputStream keystream = 
                    new BufferedOutputStream(new FileOutputStream(keyfile));
                byte[] keyhex = Hex.encode(key);
                keystream.write(keyhex, 0, keyhex.length);
                keystream.flush();
                keystream.close();
            }
            catch (IOException createKey)
            {
                System.err.println("Could not decryption create key file "+
                                    "["+keyfile+"]");
                System.exit(1);
            }
        }
        else
        {
            try
            {
                // read the key, and decode from hex encoding
                BufferedInputStream keystream = 
                    new BufferedInputStream(new FileInputStream(keyfile));
                int len = keystream.available();
                byte[] keyhex = new byte[len];
                keystream.read(keyhex, 0, len);
                key = Hex.decode(keyhex);
            }
            catch (IOException ioe)
            {
                System.err.println("Decryption key file not found, "+
                                    "or not valid ["+keyfile+"]");
                System.exit(1);
            }
        }
    }

    private void process()
    {
        /* 
         * Setup the DESede cipher engine, create a PaddedBufferedBlockCipher
         * in CBC mode.
         */
        cipher = new PaddedBufferedBlockCipher(
                                    new CBCBlockCipher(new DESedeEngine()));

        /*
         * The input and output streams are currently set up
         * appropriately, and the key bytes are ready to be
         * used.
         *
         */

        if (encrypt)
        {
            performEncrypt(key);
        }
        else
        {
            performDecrypt(key);
        }

        // after processing clean up the files
        try
        {
            in.close();
            out.flush();
            out.close();
        }
        catch (IOException closing)
        {

        }
    }
        
    /*
     * This method performs all the encryption and writes
     * the cipher text to the buffered output stream created
     * previously.
     */
    private void performEncrypt(byte[] key)
    {
        // initialise the cipher with the key bytes, for encryption
        cipher.init(true, new KeyParameter(key));

        /*
         * Create some temporary byte arrays for use in
         * encryption, make them a reasonable size so that
         * we don't spend forever reading small chunks from
         * a file.
         *
         * There is no particular reason for using getBlockSize()
         * to determine the size of the input chunk.  It just
         * was a convenient number for the example.  
         */
        // int inBlockSize = cipher.getBlockSize() * 5;
        int inBlockSize = 47;
        int outBlockSize = cipher.getOutputSize(inBlockSize);

        byte[] inblock = new byte[inBlockSize];
        byte[] outblock = new byte[outBlockSize];

        /* 
         * now, read the file, and output the chunks
         */
        try
        {
            int inL;
            int outL;
            byte[] rv = null;
            while ((inL=in.read(inblock, 0, inBlockSize)) > 0)
            {
                outL = cipher.processBytes(inblock, 0, inL, outblock, 0);
                /*
                 * Before we write anything out, we need to make sure
                 * that we've got something to write out. 
                 */
                if (outL > 0)
                {
                    rv = Hex.encode(outblock, 0, outL);
                    out.write(rv, 0, rv.length);
                    out.write('\n');
                }
            }

            try
            {
                /*
                 * Now, process the bytes that are still buffered
                 * within the cipher.
                 */
                outL = cipher.doFinal(outblock, 0);
                if (outL > 0)
                {
                    rv = Hex.encode(outblock, 0, outL);
                    out.write(rv, 0, rv.length);
                    out.write('\n');
                }
            }
            catch (CryptoException ce)
            {

            }
        }
        catch (IOException ioeread)
        {
            ioeread.printStackTrace();
        }
    }

    /*
     * This method performs all the decryption and writes
     * the plain text to the buffered output stream created
     * previously.
     */
    private void performDecrypt(byte[] key)
    {    
        // initialise the cipher for decryption
        cipher.init(false, new KeyParameter(key));

        /* 
         * As the decryption is from our preformatted file,
         * and we know that it's a hex encoded format, then
         * we wrap the InputStream with a BufferedReader
         * so that we can read it easily.
         */
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        /* 
         * now, read the file, and output the chunks
         */
        try
        {
            int outL;
            byte[] inblock = null;
            byte[] outblock = null;
            String rv = null;
            while ((rv = br.readLine()) != null)
            {
                inblock = Hex.decode(rv);
                outblock = new byte[cipher.getOutputSize(inblock.length)];

                outL = cipher.processBytes(inblock, 0, inblock.length, 
                                            outblock, 0);
                /*
                 * Before we write anything out, we need to make sure
                 * that we've got something to write out. 
                 */
                if (outL > 0)
                {
                    out.write(outblock, 0, outL);
                }
            }

            try
            {
                /*
                 * Now, process the bytes that are still buffered
                 * within the cipher.
                 */
                outL = cipher.doFinal(outblock, 0);
                if (outL > 0)
                {
                    out.write(outblock, 0, outL);
                }
            }
            catch (CryptoException ce)
            {

            }
        }
        catch (IOException ioeread)
        {
            ioeread.printStackTrace();
        }
    }

}