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 {
16 public class KeyBuilder {
18 static private RandomNumberGenerator rng;
22 rng = RandomNumberGenerator.Create ();
25 static public byte[] Key (int size)
27 byte[] key = new byte [size];
32 static public byte[] IV (int size)
34 byte[] iv = new byte [size];
40 // Process an array as a sequence of blocks
41 public class BlockProcessor {
42 private ICryptoTransform transform;
44 private int blockSize; // in bytes (not in bits)
45 private int blockCount;
47 public BlockProcessor (ICryptoTransform transform)
48 : this (transform, transform.InputBlockSize) {}
50 // some Transforms (like HashAlgorithm descendant) return 1 for
51 // block size (which isn't their real internal block size)
52 public BlockProcessor (ICryptoTransform transform, int blockSize)
54 this.transform = transform;
55 this.blockSize = blockSize;
56 block = new byte [blockSize];
61 // zeroize our block (so we don't retain any information)
62 Array.Clear (block, 0, blockSize);
65 public void Initialize ()
67 Array.Clear (block, 0, blockSize);
71 public void Core (byte[] rgb)
73 Core (rgb, 0, rgb.Length);
76 public void Core (byte[] rgb, int ib, int cb)
78 // 1. fill the rest of the "block"
79 int n = System.Math.Min (blockSize - blockCount, cb);
80 Array.Copy (rgb, ib, block, blockCount, n);
83 // 2. if block is full then transform it
84 if (blockCount == blockSize) {
85 transform.TransformBlock (block, 0, blockSize, block, 0);
87 // 3. transform any other full block in specified buffer
88 int b = (int) ((cb - n) / blockSize);
89 for (int i=0; i < b; i++) {
90 transform.TransformBlock (rgb, n, blockSize, block, 0);
94 // 4. if data is still present fill the "block" with the remainder
97 Array.Copy (rgb, n, block, 0, blockCount);
101 public byte[] Final ()
103 return transform.TransformFinalBlock (block, 0, blockCount);