/// <remarks> /// Encrypts the key package buffer /// </remarks> private void TransformBuffer(byte[] KeyData, byte[] Salt) { byte[] kvm = new byte[48]; // use salt to derive key and counter vector using (Keccak512 digest = new Keccak512(384)) kvm = digest.ComputeHash(Salt); byte[] key = new byte[32]; byte[] iv = new byte[16]; Buffer.BlockCopy(kvm, 0, key, 0, key.Length); Buffer.BlockCopy(kvm, key.Length, iv, 0, iv.Length); byte[] outData = new byte[KeyData.Length]; using (KeyParams keyparam = new KeyParams(key, iv)) { // 32 rounds of serpent using (CTR cipher = new CTR(new SHX())) { cipher.Initialize(true, keyparam); cipher.Transform(KeyData, outData); } } Buffer.BlockCopy(outData, 0, KeyData, 0, KeyData.Length); }
/// <summary> /// Assigns the rank to each of the teams based on the sum of the positions. /// Do not mix A and B teams. /// </summary> /// <param name="teams">You must always pass all teams in a championship to this parameter</param> public static void assignPointsAndRanks(ChampionshipTeamResult[] ChampionshipTeams, ScoringTeam[] teams) { if (teams == null) { return; } // For each of the Championship teams loop through each of the scoring teams and sum their points foreach (ChampionshipTeamResult CTR in ChampionshipTeams) { foreach (ScoringTeam sc in teams.Where(t => t.Team == CTR.Team))// teams.OrderBy(f => f.sumOfPositions)) { if (sc.Points == 0) { continue; } CTR.Points += sc.Points; CTR.addPosition(sc.sumOfPositions); } } int rankCounter = 1; // Set the rank value of the championship teams foreach (ChampionshipTeamResult CTR in ChampionshipTeams.OrderByDescending(c => c.Points)) { CTR.Rank = rankCounter++; } }
private void PerformTest() { byte[] iv = Hex.Decode("F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF"); using (ICipherMode mode = new CTR(new RDX())) { // NIST vectors for (int i = 0; i != _keys.Length; i++) { mode.Init(true, _keys[i], iv); for (int j = 0; j != _plainText.Length; j++) { byte[] enc = new byte[16]; mode.Transform(_plainText[j], enc); if (Compare.AreEqual(enc, _cipherText[i, j]) == false) throw new Exception("SICTest encrypted arrays are not equal!"); } // decrypt mode.Init(false, _keys[i], iv); for (int j = 0; j != _plainText.Length; j++) { byte[] dec = new byte[16]; mode.Transform(_cipherText[i, j], dec); if (Compare.AreEqual(dec, _plainText[j]) == false) throw new Exception("SICTest decrypted arrays are not equal!"); } } } }
//public static string DecryptStream(Stream str, string keyStrBase64) //{ // byte[] keyBytes = Convert.FromBase64String(keyStrBase64); // string keyStr = Encoding.UTF8.GetString(keyBytes); // Security.Encryption.EncryptedData encryptedData = Security.Encryption.EncryptedData.DeserializeJSON(keyStr); // encryptedData.Content = str.ReadFully(); // return Security.Encryption.DecryptToString(encryptedData); //} public static byte[] Decrypt(byte[] dataIn, KeyParams keyParams) //, string passphrase = null) { //byte[] decryptedData = null; ////KeyParams kp = new KeyParams(keyParams.Key, keyParams.IV, new byte[3] { 1, 2, 3 }); // RSM: Rijndael and Serpent merged. HKDF key schedule and up to 42 rounds of diffusion using (ICipherMode cipher = new CTR(new RSM(42, 32))) // TSM(32))) //, 32))) // TODO: Test TSM! ... for RSM: RSM(18, 32) { // init with key and iv //////cipher.Initialize(false, keyParams); //////using (CipherStream sc = new CipherStream(cipher)) //////{ ////// MemoryStream dataOut = new MemoryStream(); ////// sc.Initialize(false, keyParams); ////// // encrypt the buffer ////// sc.Write(new MemoryStream(dataIn), dataOut); ////// return dataOut.ToArray(); //////} //////////using (CompressionCipher cstrm = new CompressionCipher(true, cipher)) using (CompressionCipher cstrm = new CompressionCipher(cipher)) { using (MemoryStream dataInStream = new MemoryStream(dataIn)) using (MemoryStream dataOutStream = new MemoryStream()) { //////var dataInMemStream = ; // TODO: rollup in Initialize cstrm.Initialize(false, keyParams); cstrm.Write(dataInStream, dataOutStream); return(dataOutStream.ToArray()); } } } }
public void GoToOcean(List <SubNodeCTR> _nodeCtrs, CTR _ctr, List <GameObject> TitleList) { // ValueSheet.CurrentNodeCtr = _nodeCtrs; ToOceanGeneral(new Vector3(0, 15.3f, 300f), new Vector3(0, 33.3f, -68.1f), true, false, _ctr); _nodeCtrs[0].imageClusterCtr.Display(0, TitleList); // MainCtr.instance.TURN_ON_OFFChild_Sub(_ctr, true, _nodeCtrs); }
private CTR MapGrower(Grower grower, int growerIndex, Dictionary <int, string> keyToIsoId) { var isoGrower = new CTR { B = grower.Name }; isoGrower.A = isoGrower.GetIsoId(growerIndex); keyToIsoId.Add(grower.Id.ReferenceId, isoGrower.A); return(isoGrower); }
public void WriteByte(uint Offset, byte Value) { switch (Offset) { case 2: // CFG9_RST11 bool Reset = (Value << 31 != 1); if (Reset != false) { CTR.SetCPU(CPU.Type.ARM11, Reset); } break; } }
/// <summary> /// Función encargada de descifrar el texto proporcionado por el usuario mediante 56 rondas del algoritmo Serpent /// </summary> /// <param name="txtCifrado">Cadena en Base64 con el texto cifrado</param> /// <returns>Cadena de texto plano con el texto descifrado</returns> public static string DescifraTxt(string txtCifrado) { using (var cifradoCEX = new CTR(new SPX(56))) { byte[] txtBytesCifrado = Convert.FromBase64String(txtCifrado); byte[] txtBytes = new byte[txtBytesCifrado.Length]; cifradoCEX.Initialize(true, new KeyParams(setClave(64), setClave(16))); cifradoCEX.Transform(txtBytesCifrado, txtBytes); return(Encoding.UTF32.GetString(txtBytes)); } }
/// <summary> /// Función encargada de cifrar el texto proporcionado por el usuario mediante 56 rondas del algoritmo Serpent /// </summary> /// <param name="txtPlano">Cadena con el texto en formato plano a cifrar</param> /// <returns>Cadena en Base64 con el texto cifrado</returns> public static string CifraTxt(string txtPlano) { using (var cifradoCEX = new CTR(new SPX(56))) { byte[] txtBytes = Encoding.UTF32.GetBytes(txtPlano); byte[] txtBytesCifrado = new byte[txtBytes.Length]; cifradoCEX.Initialize(true, new KeyParams(setClave(64), setClave(16))); cifradoCEX.Transform(txtBytes, txtBytesCifrado); return(Convert.ToBase64String(txtBytesCifrado)); } }
private void CTRTest(byte[] Key, byte[, ][] Input, byte[, ][] Output) { byte[] outBytes = new byte[16]; byte[] iv = _vectors[1]; int index = 24; if (Key.Length == 24) { index = 26; } else if (Key.Length == 32) { index = 28; } using (CTR mode = new CTR(new RHX())) { mode.Initialize(true, new KeyParams(Key, iv)); for (int i = 0; i < 4; i++) { mode.Transform(Input[index, i], outBytes); if (Evaluate.AreEqual(outBytes, Output[index, i]) == false) { throw new Exception("CTR Mode: Encrypted arrays are not equal!"); } } } index++; using (CTR mode = new CTR(new RHX())) { mode.Initialize(false, new KeyParams(Key, iv)); for (int i = 0; i < 4; i++) { mode.Transform(Input[index, i], outBytes); if (Evaluate.AreEqual(outBytes, _output[index, i]) == false) { throw new Exception("CTR Mode: Decrypted arrays are not equal!"); } } } }
public TempPrice GetTempPrice(string id, string value, string type, out decimal price) { ProductPrice pP = GetById(Convert.ToInt32(id)); TempPrice tP = new TempPrice(); decimal Price; decimal PriceSell; decimal CTR; string tempvalue = value.Replace(",", "."); if (type == "1") { Price = Convert.ToDecimal(tempvalue); } else if (type == "2") { Price = (-((pP.Product.BasePrices[0].PricePurchase * pP.Product.BasePrices[0].PricePurchaseCurrency.Value) / (((Convert.ToDecimal(tempvalue) / 100) - 1) * ((100 - pP.PriceList.Discount.MaxDiscount) / 100))) / pP.PriceSellCurrency.Value); } else { Price = pP.Price * (1 + (Convert.ToDecimal(tempvalue) / 100)); } PriceSell = ((Price * pP.PriceCurrency.Value) * (100 - pP.PriceList.Discount.MaxDiscount) / 100) / pP.PriceSellCurrency.Value; if (!(pP.Product.BasePrices[0].PricePurchase == 0)) { CTR = (1 - ((pP.Product.BasePrices[0].PricePurchase * pP.Product.BasePrices[0].PricePurchaseCurrency.Value) / (PriceSell * pP.PriceSellCurrency.Value))) * 100; } else { CTR = 0; } price = Price; tP.NewPrice = pP.PriceCurrency.Description + " " + Price.ToString("#,##0.00"); tP.NewCtr = CTR.ToString("##0.00") + " %"; tP.OriginalPrice = pP.PriceCurrency.Description + " " + pP.Price.ToString("#,##0.00"); tP.NewPriceWF = Price.ToString(); tP.OriginalPriceWF = pP.Price; return(tP); }
public void TurnOnOne(CTR ctr) { if (ctr.GetType() == defaultNodeParentCtr.GetType()) { defaultNodeParentCtr.TurnOn_Off(true, ValueSheet.nodeCtrs); // gongyiNodeParentCtr.TurnOn_Off(false, ValueSheet.Gongyi_nodeCtrs); // eCONodeParentCtr.TurnOn_Off(false, ValueSheet.ECO_nodeCtrs); } //else if (ctr.GetType() == gongyiNodeParentCtr.GetType()) //{ // defaultNodeParentCtr.TurnOn_Off(false, ValueSheet.nodeCtrs); // gongyiNodeParentCtr.TurnOn_Off(true, ValueSheet.Gongyi_nodeCtrs); // eCONodeParentCtr.TurnOn_Off(false, ValueSheet.ECO_nodeCtrs); //} //else if (ctr.GetType() == eCONodeParentCtr.GetType()) { // defaultNodeParentCtr.TurnOn_Off(false, ValueSheet.nodeCtrs); // gongyiNodeParentCtr.TurnOn_Off(false, ValueSheet.Gongyi_nodeCtrs); // eCONodeParentCtr.TurnOn_Off(true, ValueSheet.ECO_nodeCtrs); //} }
/// <summary> /// Compress and encrypt a file, then decrypt and deflate to an output directory /// </summary> /// /// <param name="InputDirectory">The path of the folder to be archived</param> /// <param name="OutputDirectory">The decompressed files output directory</param> /// <param name="CompressedFilePath">The name and path of the new compressed and encrypted archive</param> public static void CompressionCipherTest(string InputDirectory, string OutputDirectory, string CompressedFilePath) { KeyParams kp = new KeyGenerator().GetKeyParams(32, 16); // Create an archive // // create the cipher using (ICipherMode cipher = new CTR(new RHX())) { // create the archive file using (FileStream fs = new FileStream(CompressedFilePath, FileMode.Create)) { // compress and encrypt directory using (CompressionCipher cc = new CompressionCipher(cipher)) { // set the input folder path and archive output stream cc.Initialize(true, kp); // write the compressed and encrypted archive to file cc.Deflate(InputDirectory, fs); } } } // Inflate an archive // // create the cipher using (ICipherMode cipher = new CTR(new RHX())) { // open the archive using (FileStream decmp = new FileStream(CompressedFilePath, FileMode.Open)) { // decrypt and inflate to output directory using (CompressionCipher cc = new CompressionCipher(cipher)) { // set the output folder path and archive path cc.Initialize(false, kp); // decrypt and inflate the directory cc.Inflate(OutputDirectory, decmp); } } } // manual inspection of files.. }
/// <summary> /// Outputs expected values for 512 bit keys /// </summary> /// /// <returns>State</returns> public string Get512Vector(BlockCiphers EngineType, RoundCounts Rounds, int BlockSize = 16) { IBlockCipher engine = GetCipher(EngineType, Digests.None, Rounds, BlockSize); // rounds calc automatic int keyLen = 64; byte[] key = new byte[keyLen]; byte[] iv = new byte[engine.BlockSize]; ICipherMode cipher = new CTR(engine); for (int i = 0; i < keyLen; i++) { key[i] = (byte)i; } for (int i = 0; i < iv.Length; i++) { iv[i] = (byte)i; } cipher.Initialize(true, new KeyParams(key, iv)); return(MonteCarloTest(cipher)); }
/// <summary> /// Outputs expected values for the HX Ciphers /// </summary> /// /// <returns>State</returns> public string GetHXVector(BlockCiphers EngineType, Digests DigestType, RoundCounts Rounds) { IBlockCipher engine = GetCipher(EngineType, DigestType, Rounds); int keyLen = GetKeySize(engine); byte[] key = new byte[keyLen]; byte[] iv = new byte[engine.BlockSize]; ICipherMode cipher = new CTR(engine); for (int i = 0; i < keyLen; i++) { key[i] = (byte)i; } for (int i = 0; i < iv.Length; i++) { iv[i] = (byte)i; } cipher.Initialize(true, new KeyParams(key, iv)); return(MonteCarloTest(cipher)); }
private void PerformTest() { byte[] iv = Hex.Decode("F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF"); using (ICipherMode mode = new CTR(new RDX())) { // NIST vectors for (int i = 0; i != _keys.Length; i++) { mode.Init(true, _keys[i], iv); for (int j = 0; j != _plainText.Length; j++) { byte[] enc = new byte[16]; mode.Transform(_plainText[j], enc); if (Compare.AreEqual(enc, _cipherText[i, j]) == false) { throw new Exception("SICTest encrypted arrays are not equal!"); } } // decrypt mode.Init(false, _keys[i], iv); for (int j = 0; j != _plainText.Length; j++) { byte[] dec = new byte[16]; mode.Transform(_cipherText[i, j], dec); if (Compare.AreEqual(dec, _plainText[j]) == false) { throw new Exception("SICTest decrypted arrays are not equal!"); } } } } }
public void TURN_ON_OFFChild_Sub(CTR ctr, bool B, List <SubNodeCTR> nodeCtrs) { ctr.TurnOn_Off(B, nodeCtrs); }
public void Setup() { _ctr = new CTR(); _output = new StringBuilder(); _xmlBuilder = XmlWriter.Create(_output); }
void ToOceanGeneral(Vector3 pos, Vector3 _targetPos, bool isTurnOnSideImage, bool building, CTR ctr) { //logoWellCtr.TurnOffLogoWell(); MainCtr.instance.TurnOnOne(ctr); SoundMangager.instance.Select(); //Debug.Log(VideoCtr.instance.FullScreenVideoPlayer.Control.IsPlaying()); if (VideoCtr.instance.FullScreenVideoPlayer.Control.IsPlaying()) { CanvasMangager.instance.HideAlltitleText(); VideoCtr.instance.StopFullScreenVideoPlayer(); VideoCtr.instance.FullScreenVideoPlayer.m_VideoPath = ""; Debug.Log("video to ocean"); OverRideCameraMove.instance.initializtion(pos); SoundMangager.instance.StopBGM(); SoundMangager.instance.PlayBGM("BGM"); CanvasMangager.instance.TurnOffAllTitle(); CanvasMangager.instance.ONOFF(isTurnOnSideImage, building); // StartCoroutine(CanvasMangager.instance.Fade()); } Debug.Log(CanvasMangager.instance.isInScreenProtect); if (CanvasMangager.instance.isInScreenProtect) { CanvasMangager.instance.HideAlltitleText(); VideoCtr.instance.FullScreenVideoPlayer.m_VideoPath = ""; CanvasMangager.instance.HideScreenProtect(); OverRideCameraMove.instance.initializtion(pos); SoundMangager.instance.StopBGM(); SoundMangager.instance.PlayBGM("BGM"); CanvasMangager.instance.TurnOffAllTitle(); CanvasMangager.instance.ONOFF(isTurnOnSideImage, building); //StartCoroutine(CanvasMangager.instance.Fade()); } }
/// <summary> /// Test the CipherStream class implementation /// <para>Throws an Exception on failure</</para> /// </summary> public static void StreamCipherTest() { const int BLSZ = 1024; KeyParams key; byte[] data; MemoryStream instrm; MemoryStream outstrm = new MemoryStream(); using (KeyGenerator kg = new KeyGenerator()) { // get the key key = kg.GetKeyParams(32, 16); // 2048 bytes data = kg.GetBytes(BLSZ * 2); } // data to encrypt instrm = new MemoryStream(data); // Encrypt a stream // // create the outbound cipher using (ICipherMode cipher = new CTR(new RHX())) { // set block size ((CTR)cipher).ParallelBlockSize = BLSZ; // encrypt the stream using (CipherStream sc = new CipherStream(cipher)) { sc.Initialize(true, key); // encrypt the buffer sc.Write(instrm, outstrm); } } // reset stream position outstrm.Seek(0, SeekOrigin.Begin); MemoryStream tmpstrm = new MemoryStream(); // Decrypt a stream // // create the decryption cipher using (ICipherMode cipher = new CTR(new RHX())) { // set block size ((CTR)cipher).ParallelBlockSize = BLSZ; // decrypt the stream using (CipherStream sc = new CipherStream(cipher)) { sc.Initialize(false, key); // process the encrypted bytes sc.Write(outstrm, tmpstrm); } } // compare decrypted output with data if (!Evaluate.AreEqual(tmpstrm.ToArray(), data)) { throw new Exception(); } }
public static byte[] Encrypt(byte[] dataIn, KeyParams keyParams = null) //, string passphrase = null) { //// populate a keyheader //KeyHeaderStruct keyHeader = new KeyHeaderStruct( // Engines.RHX, // cipher engine // 192, // key size in bytes // IVSizes.V128, // cipher iv size enum // CipherModes.CTR, // cipher mode enum // PaddingModes.X923, // cipher padding mode enum // BlockSizes.B128, // block size enum // RoundCounts.R18, // diffusion rounds enum // Digests.Skein512, // cipher kdf engine // 64, // mac size // Digests.Keccak); // mac digest //// create the key file //new KeyFactory(KeyPath).Create(keyHeader); ////if (keyParams == null) ////{ //// using (KeyGenerator kg = new KeyGenerator()) //// { //// keyParams = kg.GetKeyParams(192, 64, 64); //// } ////} //////encryptedData.Key = keyParams.Key; //////encryptedData.Iv = keyParams.IV; //////encryptedData.Salt = keyParams.IKM; // RSM: Rijndael and Serpent merged. HKDF key schedule and up to 42 rounds of diffusion using (ICipherMode cipher = new CTR(new RSM(42, 32))) // TSM(32))) //, 32))) // TODO: 42, 32))) ... for RSM: RSM(18, 32) { // init with key and iv //////cipher.Initialize(true, keyParams); /* * The Compression cipher wraps the StreamCipher class by first compressing a target directory, then encrypting the compressed file. Decryption inflates the directory to a target path. */ ////using (CompressionCipher cstrm = new CompressionCipher(true, cipher)) /// //////using (CipherStream sc = new CipherStream(cipher)) //////{ ////// MemoryStream dataOut = new MemoryStream(); ////// sc.Initialize(true, keyParams); ////// // encrypt the buffer ////// sc.Write(new MemoryStream(dataIn), dataOut); ////// return dataOut.ToArray(); //////} using (CompressionCipher cstrm = new CompressionCipher(cipher)) { using (MemoryStream dataInStream = new MemoryStream(dataIn)) using (MemoryStream dataOutStream = new MemoryStream()) { //////var dataInMemStream = ; // TODO: rollup in Initialize cstrm.Initialize(true, keyParams); cstrm.Write(dataInStream, dataOutStream); return(dataOutStream.ToArray()); } } } //////return encryptedData; }
/// <summary> /// Test the PacketCipher class implementation /// <para>Throws an Exception on failure</</para> /// </summary> public static void PacketCipherTest() { const int BLSZ = 1024; KeyParams key; byte[] data; MemoryStream instrm; MemoryStream outstrm = new MemoryStream(); using (KeyGenerator kg = new KeyGenerator()) { // get the key key = kg.GetKeyParams(32, 16); // 2 * 1200 byte packets data = kg.GetBytes(BLSZ * 2); } // data to encrypt instrm = new MemoryStream(data); // Encrypt a stream // // create the outbound cipher using (ICipherMode cipher = new CTR(new RHX())) { // initialize the cipher for encryption cipher.Initialize(true, key); // set block size ((CTR)cipher).ParallelBlockSize = BLSZ; // encrypt the stream using (PacketCipher pc = new PacketCipher(cipher)) { byte[] inbuffer = new byte[BLSZ]; byte[] outbuffer = new byte[BLSZ]; int bytesread = 0; while ((bytesread = instrm.Read(inbuffer, 0, BLSZ)) > 0) { // encrypt the buffer pc.Write(inbuffer, 0, outbuffer, 0, BLSZ); // add it to the output stream outstrm.Write(outbuffer, 0, outbuffer.Length); } } } // reset stream position outstrm.Seek(0, SeekOrigin.Begin); MemoryStream tmpstrm = new MemoryStream(); // Decrypt a stream // // create the inbound cipher using (ICipherMode cipher = new CTR(new RHX())) { // initialize the cipher for decryption cipher.Initialize(false, key); // set block size ((CTR)cipher).ParallelBlockSize = BLSZ; // decrypt the stream using (PacketCipher pc = new PacketCipher(cipher)) { byte[] inbuffer = new byte[BLSZ]; byte[] outbuffer = new byte[BLSZ]; int bytesread = 0; while ((bytesread = outstrm.Read(inbuffer, 0, BLSZ)) > 0) { // process the encrypted bytes pc.Write(inbuffer, 0, outbuffer, 0, BLSZ); // write to stream tmpstrm.Write(outbuffer, 0, outbuffer.Length); } } } // compare decrypted output with data if (!Evaluate.AreEqual(tmpstrm.ToArray(), data)) { throw new Exception(); } }
void ToOceanGeneral(Vector3 pos, Vector3 _targetPos, bool isTurnOnSideImage, int Title, bool building, CTR ctr, List <GameObject> TitleList) { logoWellCtr.TurnOffLogoWell(); MainCtr.instance.TurnOnOne(ctr); SoundMangager.instance.Select(); VideoCtr.instance.StopFullScreenVideoPlayer(); StartCoroutine(CameraMover.instance.initialization(pos, _targetPos)); CanvasMangager.instance.TurnOffAllTitle(); CanvasMangager.instance.ONOFF(isTurnOnSideImage, Title, building, TitleList); StartCoroutine(CanvasMangager.instance.Fade()); SoundMangager.instance.StopBGM(); SoundMangager.instance.PlayBGM("BGM"); }
private void ParallelTest() { byte[] data; byte[] dec1; byte[] dec2; byte[] enc1; byte[] enc2; int blockSize; KeyParams keyParam = new KeyParams(new byte[32], new byte[16]); // CTR mode using (CTR cipher = new CTR(new RHX())) { data = GetBytes(1036); // how to calculate an ideal block size int plen = (data.Length / cipher.ParallelMinimumSize) * cipher.ParallelMinimumSize; // you can factor it up or down or use a default if (plen > cipher.ParallelMaximumSize) { plen = 1024; } // set parallel block size cipher.ParallelBlockSize = plen; // parallel 1 cipher.Initialize(true, keyParam); cipher.IsParallel = true; blockSize = cipher.ParallelBlockSize; enc1 = Transform2(cipher, data, blockSize); // linear 1 cipher.Initialize(true, keyParam); cipher.IsParallel = false; blockSize = cipher.BlockSize; enc2 = Transform2(cipher, data, blockSize); if (Evaluate.AreEqual(enc1, enc2) == false) { throw new Exception("Parallel CTR: Encrypted output is not equal!"); } // encrypt // // parallel 2 cipher.Initialize(true, keyParam); cipher.IsParallel = true; blockSize = cipher.ParallelBlockSize; enc1 = Transform1(cipher, data, blockSize); if (Evaluate.AreEqual(enc1, enc2) == false) { throw new Exception("Parallel CTR: Encrypted output is not equal!"); } // linear 2 cipher.Initialize(true, keyParam); cipher.IsParallel = false; blockSize = cipher.BlockSize; enc2 = Transform2(cipher, data, blockSize); if (Evaluate.AreEqual(enc1, enc2) == false) { throw new Exception("Parallel CTR: Encrypted output is not equal!"); } // decrypt // // parallel 1 cipher.Initialize(false, keyParam); cipher.IsParallel = true; blockSize = cipher.ParallelBlockSize; dec1 = Transform1(cipher, enc1, blockSize); // parallel 2 cipher.Initialize(false, keyParam); cipher.IsParallel = true; blockSize = cipher.ParallelBlockSize; dec2 = Transform2(cipher, enc2, blockSize); if (Evaluate.AreEqual(dec1, dec2) == false) { throw new Exception("Parallel CTR: Decrypted output is not equal!"); } // linear 1 cipher.Initialize(false, keyParam); cipher.IsParallel = false; blockSize = cipher.BlockSize; dec2 = Transform1(cipher, enc1, blockSize); if (Evaluate.AreEqual(dec1, dec2) == false) { throw new Exception("Parallel CTR: Decrypted output is not equal!"); } // linear 2 cipher.Initialize(false, keyParam); cipher.IsParallel = false; blockSize = cipher.BlockSize; dec2 = Transform2(cipher, enc2, blockSize); if (Evaluate.AreEqual(dec1, dec2) == false) { throw new Exception("Parallel CTR: Decrypted output is not equal!"); } } if (Evaluate.AreEqual(data, dec1) == false) { throw new Exception("Parallel CTR: Decrypted output is not equal!"); } if (Evaluate.AreEqual(data, dec2) == false) { throw new Exception("Parallel CTR: Decrypted output is not equal!"); } OnProgress(new TestEventArgs("Passed Parallel CTR encryption and decryption tests..")); // CBC mode using (CBC cipher = new CBC(new RHX())) { // must be divisible by block size, add padding if required data = GetBytes(2048); // encrypt cipher.ParallelBlockSize = 1024; // t1: encrypt only in normal mode for cbc cipher.Initialize(true, keyParam); blockSize = cipher.BlockSize; enc1 = Transform1(cipher, data, blockSize); // t2 cipher.Initialize(true, keyParam); blockSize = cipher.BlockSize; enc2 = Transform2(cipher, data, blockSize); if (Evaluate.AreEqual(enc1, enc2) == false) { throw new Exception("Parallel CBC: Decrypted output is not equal!"); } // decrypt // // t1 parallel cipher.Initialize(false, keyParam); cipher.IsParallel = true; blockSize = cipher.ParallelBlockSize; dec1 = Transform1(cipher, enc1, blockSize); // t1 linear cipher.Initialize(false, keyParam); cipher.IsParallel = false; blockSize = cipher.BlockSize; dec2 = Transform1(cipher, enc2, blockSize); if (Evaluate.AreEqual(dec1, dec2) == false) { throw new Exception("Parallel CBC: Decrypted output is not equal!"); } // t2 parallel cipher.Initialize(false, keyParam); cipher.IsParallel = true; blockSize = cipher.ParallelBlockSize; dec1 = Transform2(cipher, enc2, blockSize); // t2 linear cipher.Initialize(false, keyParam); cipher.IsParallel = false; blockSize = cipher.BlockSize; dec2 = Transform2(cipher, enc1, blockSize); if (Evaluate.AreEqual(dec1, dec2) == false) { throw new Exception("Parallel CBC: Decrypted output is not equal!"); } } if (Evaluate.AreEqual(dec1, data) == false) { throw new Exception("Parallel CBC: Decrypted output is not equal!"); } if (Evaluate.AreEqual(dec2, data) == false) { throw new Exception("Parallel CBC: Decrypted output is not equal!"); } OnProgress(new TestEventArgs("Passed Parallel CBC decryption tests..")); // CFB mode using (CFB cipher = new CFB(new RHX())) { // must be divisible by block size, add padding if required data = GetBytes(2048); // encrypt cipher.ParallelBlockSize = 1024; // t1: encrypt only in normal mode for cfb cipher.Initialize(true, keyParam); blockSize = cipher.BlockSize; enc1 = Transform1(cipher, data, blockSize); // t2 cipher.Initialize(true, keyParam); blockSize = cipher.BlockSize; enc2 = Transform2(cipher, data, blockSize); if (Evaluate.AreEqual(enc1, enc2) == false) { throw new Exception("Parallel CFB: Decrypted output is not equal!"); } // decrypt // // t1 parallel cipher.Initialize(false, keyParam); cipher.IsParallel = true; blockSize = cipher.ParallelBlockSize; dec1 = Transform1(cipher, enc1, blockSize); // t1 linear cipher.Initialize(false, keyParam); cipher.IsParallel = false; blockSize = cipher.BlockSize; dec2 = Transform1(cipher, enc2, blockSize); if (Evaluate.AreEqual(dec1, dec2) == false) { throw new Exception("Parallel CFB: Decrypted output is not equal!"); } // t2 parallel cipher.Initialize(false, keyParam); cipher.IsParallel = true; blockSize = cipher.ParallelBlockSize; dec1 = Transform2(cipher, enc2, blockSize); // t2 linear cipher.Initialize(false, keyParam); cipher.IsParallel = false; blockSize = cipher.BlockSize; dec2 = Transform2(cipher, enc1, blockSize); if (Evaluate.AreEqual(dec1, dec2) == false) { throw new Exception("Parallel CFB: Decrypted output is not equal!"); } } if (Evaluate.AreEqual(data, dec1) == false) { throw new Exception("Parallel CFB: Decrypted output is not equal!"); } if (Evaluate.AreEqual(data, dec2) == false) { throw new Exception("Parallel CFB: Decrypted output is not equal!"); } OnProgress(new TestEventArgs("Passed Parallel CFB decryption tests..")); // dispose container keyParam.Dispose(); }
private void ParametersTest() { AllocateRandom(ref _iv, 16); AllocateRandom(ref _key, 32); AllocateRandom(ref _plnText, 1); KeyParams kp = new KeyParams(_key, _iv); _cmpText = new byte[1]; _decText = new byte[1]; _encText = new byte[1]; RHX engine = new RHX(); // 1 byte w/ byte arrays { CTR cipher = new CTR(engine, false); CipherStream cs = new CipherStream(cipher); cs.Initialize(true, kp); cs.Write(_plnText, 0, ref _encText, 0); cs.Initialize(false, kp); cs.Write(_encText, 0, ref _decText, 0); if (!Evaluate.AreEqual(_decText, _plnText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } cipher.Dispose(); } // 1 byte w/ stream { CTR cipher = new CTR(engine, false); CipherStream cs = new CipherStream(cipher); cs.Initialize(true, kp); AllocateRandom(ref _plnText, 1); MemoryStream mIn = new MemoryStream(_plnText); MemoryStream mOut = new MemoryStream(); cs.Write(mIn, mOut); cs.Initialize(false, kp); MemoryStream mRes = new MemoryStream(); mOut.Seek(0, SeekOrigin.Begin); cs.Write(mOut, mRes); if (!Evaluate.AreEqual(mRes.ToArray(), _plnText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } cipher.Dispose(); } // partial block w/ byte arrays { CTR cipher = new CTR(engine, false); CipherStream cs = new CipherStream(cipher); AllocateRandom(ref _plnText, 15); Array.Resize(ref _decText, 15); Array.Resize(ref _encText, 15); cs.Initialize(true, kp); cs.Write(_plnText, 0, ref _encText, 0); cs.Initialize(false, kp); cs.Write(_encText, 0, ref _decText, 0); if (!Evaluate.AreEqual(_decText, _plnText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } cipher.Dispose(); } // partial block w/ stream { CTR cipher = new CTR(engine, false); CipherStream cs = new CipherStream(cipher); AllocateRandom(ref _plnText, 15); Array.Resize(ref _decText, 15); Array.Resize(ref _encText, 15); cs.Initialize(true, kp); MemoryStream mIn = new MemoryStream(_plnText); MemoryStream mOut = new MemoryStream(); cs.Write(mIn, mOut); cs.Initialize(false, kp); MemoryStream mRes = new MemoryStream(); mOut.Seek(0, SeekOrigin.Begin); cs.Write(mOut, mRes); if (!Evaluate.AreEqual(mRes.ToArray(), _plnText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } cipher.Dispose(); } // random block sizes w/ byte arrays { for (int i = 0; i < 100; i++) { CTR cipher = new CTR(engine, false); int sze = AllocateRandom(ref _plnText); _decText = new byte[sze]; _encText = new byte[sze]; CipherStream cs = new CipherStream(cipher); cs.Initialize(true, kp); cs.Write(_plnText, 0, ref _encText, 0); cs.Initialize(false, kp); cs.Write(_encText, 0, ref _decText, 0); if (!Evaluate.AreEqual(_decText, _plnText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } cipher.Dispose(); } } // random block sizes w/ stream { for (int i = 0; i < 100; i++) { CTR cipher = new CTR(engine, false); int sze = AllocateRandom(ref _plnText); _decText = new byte[sze]; _encText = new byte[sze]; CipherStream cs = new CipherStream(cipher); cs.Initialize(true, kp); MemoryStream mIn = new MemoryStream(_plnText); MemoryStream mOut = new MemoryStream(); cs.Write(mIn, mOut); cs.Initialize(false, kp); MemoryStream mRes = new MemoryStream(); mOut.Seek(0, SeekOrigin.Begin); cs.Write(mOut, mRes); if (!Evaluate.AreEqual(mRes.ToArray(), _plnText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } cipher.Dispose(); } } engine.Dispose(); }
public string[] GetData() { return(new string[] { name, type, price.ToString() + "$", count.ToString(), unit, CR.ToString(), CTR.ToString(), Users.ToString(), Clicks.ToString(), Views.ToString(), UserPrice.ToString() + "$" }); }
private void CtrModeTest() { AllocateRandom(ref _iv, 16); AllocateRandom(ref _key, 32); KeyParams kp = new KeyParams(_key, _iv); RHX eng = new RHX(); CTR cipher = new CTR(eng); CTR cipher2 = new CTR(eng); CipherStream cs = new CipherStream(cipher2); cipher.IsParallel = false; // ctr test for (int i = 0; i < 10; i++) { int sze = AllocateRandom(ref _plnText); int prlBlock = sze - (sze % (cipher.BlockSize * _processorCount)); _encText = new byte[sze]; _cmpText = new byte[sze]; _decText = new byte[sze]; cipher.ParallelBlockSize = prlBlock; cipher2.ParallelBlockSize = prlBlock; MemoryStream mIn = new MemoryStream(_plnText); MemoryStream mOut = new MemoryStream(); MemoryStream mRes = new MemoryStream(); // *** Compare encryption output *** // // local processor cipher.Initialize(true, kp); BlockCTR(cipher, _plnText, 0, _encText, 0); // streamcipher linear mode cs.IsParallel = false; // memorystream interface cs.Initialize(true, kp); cs.Write(mIn, mOut); if (!Evaluate.AreEqual(mOut.ToArray(), _encText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } // byte array interface cs.Initialize(true, kp); cs.Write(_plnText, 0, ref _cmpText, 0); if (!Evaluate.AreEqual(_cmpText, _encText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } mIn.Seek(0, SeekOrigin.Begin); mOut.Seek(0, SeekOrigin.Begin); cs.IsParallel = true; cs.Initialize(true, kp); cs.Write(mIn, mOut); if (!Evaluate.AreEqual(mOut.ToArray(), _encText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } // byte array interface cs.Initialize(true, kp); cs.Write(_plnText, 0, ref _cmpText, 0); if (!Evaluate.AreEqual(_cmpText, _encText)) { throw new Exception("CipherStreamTest: Encrypted arrays are not equal!"); } // ***compare decryption output *** // // local processor cipher.Initialize(false, kp); BlockCTR(cipher, _encText, 0, _decText, 0); if (!Evaluate.AreEqual(_plnText, _decText)) { throw new Exception("CipherStreamTest: Decrypted arrays are not equal!"); } // decrypt linear mode cs.IsParallel = false; mOut.Seek(0, SeekOrigin.Begin); cs.Initialize(false, kp); cs.Write(mOut, mRes); if (!Evaluate.AreEqual(mRes.ToArray(), _decText)) { throw new Exception("CipherStreamTest: Decrypted arrays are not equal!"); } // byte array interface cs.Initialize(false, kp); cs.Write(_encText, 0, ref _cmpText, 0); if (!Evaluate.AreEqual(_cmpText, _decText)) { throw new Exception("CipherStreamTest: Decrypted arrays are not equal!"); } // decrypt parallel mode cs.IsParallel = true; mOut.Seek(0, SeekOrigin.Begin); mRes.Seek(0, SeekOrigin.Begin); cs.Initialize(false, kp); cs.Write(mOut, mRes); if (!Evaluate.AreEqual(mRes.ToArray(), _decText)) { throw new Exception("CipherStreamTest: Decrypted arrays are not equal!"); } // byte array interface cs.Initialize(false, kp); cs.Write(_encText, 0, ref _cmpText, 0); if (!Evaluate.AreEqual(_cmpText, _decText)) { throw new Exception("CipherStreamTest: Decrypted arrays are not equal!"); } } eng.Dispose(); }