2 // Mono.Security.Cryptography.CryptoTools
3 // Shared class for common cryptographic functionalities
6 // Sebastien Pouliot (spouliot@motus.com)
8 // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
12 using System.Security.Cryptography;
14 namespace Mono.Security.Cryptography {
23 static private RandomNumberGenerator rng;
27 rng = RandomNumberGenerator.Create ();
30 static public byte[] Key (int size)
32 byte[] key = new byte [size];
37 static public byte[] IV (int size)
39 byte[] iv = new byte [size];
45 // Process an array as a sequence of blocks
51 class BlockProcessor {
52 private ICryptoTransform transform;
54 private int blockSize; // in bytes (not in bits)
55 private int blockCount;
57 public BlockProcessor (ICryptoTransform transform)
58 : this (transform, transform.InputBlockSize) {}
60 // some Transforms (like HashAlgorithm descendant) return 1 for
61 // block size (which isn't their real internal block size)
62 public BlockProcessor (ICryptoTransform transform, int blockSize)
64 this.transform = transform;
65 this.blockSize = blockSize;
66 block = new byte [blockSize];
71 // zeroize our block (so we don't retain any information)
72 Array.Clear (block, 0, blockSize);
75 public void Initialize ()
77 Array.Clear (block, 0, blockSize);
81 public void Core (byte[] rgb)
83 Core (rgb, 0, rgb.Length);
86 public void Core (byte[] rgb, int ib, int cb)
88 // 1. fill the rest of the "block"
89 int n = System.Math.Min (blockSize - blockCount, cb);
90 Array.Copy (rgb, ib, block, blockCount, n);
93 // 2. if block is full then transform it
94 if (blockCount == blockSize) {
95 transform.TransformBlock (block, 0, blockSize, block, 0);
97 // 3. transform any other full block in specified buffer
98 int b = (int) ((cb - n) / blockSize);
99 for (int i=0; i < b; i++) {
100 transform.TransformBlock (rgb, n, blockSize, block, 0);
104 // 4. if data is still present fill the "block" with the remainder
107 Array.Copy (rgb, n, block, 0, blockCount);
111 public byte[] Final ()
113 return transform.TransformFinalBlock (block, 0, blockCount);