// Encrypt/decrypt using the given key public byte[] encode(byte[] data) { _wkCipher.Init(true, this.key); byte[] outputBytes = new byte[_wkCipher.GetOutputSize(data.Length)]; int length = _wkCipher.ProcessBytes(data, outputBytes, 0); _wkCipher.DoFinal(outputBytes, length); //Do the final block return(outputBytes); }
private byte[] EncryptBlock(byte[] input, int inOff, int inLen, byte[] macData) { // Block cipher mode. byte[] k1 = new byte[((IesWithCipherParameters)_iesParameters).CipherKeySize / 8]; byte[] k2 = new byte[_iesParameters.MacKeySize / 8]; byte[] k = _kdfKey; Array.Copy(k, 0, k1, 0, k1.Length); Array.Copy(k, k1.Length, k2, 0, k2.Length); _cipher.Init(true, new ParametersWithIV(new KeyParameter(k1), _iv)); byte[] c = new byte[_cipher.GetOutputSize(inLen)]; int len = _cipher.ProcessBytes(input, inOff, inLen, c, 0); len += _cipher.DoFinal(c, len); // Convert the length of the encoding vector into a byte array. byte[] p2 = _iesParameters.GetEncodingV(); // Apply the MAC. byte[] T = new byte[_mac.GetMacSize()]; byte[] k2A = new byte[_hash.GetDigestSize()]; _hash.Reset(); _hash.BlockUpdate(k2, 0, k2.Length); _hash.DoFinal(k2A, 0); _mac.Init(new KeyParameter(k2A)); _mac.BlockUpdate(_iv, 0, _iv.Length); _mac.BlockUpdate(c, 0, c.Length); if (p2 != null) { _mac.BlockUpdate(p2, 0, p2.Length); } if (macData != null) { _mac.BlockUpdate(macData, 0, macData.Length); } _mac.DoFinal(T, 0); // Output the double (C,T). byte[] output = new byte[len + T.Length]; Array.Copy(c, 0, output, 0, len); Array.Copy(T, 0, output, len, T.Length); return(output); }
private static MemoryStream DecryptAes(Stream inputStream, BufferedBlockCipher cipher, long length) { int blockSize = cipher.GetBlockSize(); int inputLength = (int)length; int paddedLength = inputLength; if (paddedLength % blockSize > 0) { paddedLength += blockSize - paddedLength % blockSize; } byte[] input = new byte[paddedLength]; byte[] output = new byte[cipher.GetOutputSize(paddedLength)]; inputStream.Read(input, 0, inputLength); int len = cipher.ProcessBytes(input, 0, input.Length, output, 0); cipher.DoFinal(output, len); MemoryStream outputStream = new MemoryStream(); outputStream.Write(output, 0, inputLength); outputStream.Seek(0, SeekOrigin.Begin); return(outputStream); }
public static byte[] AESDecrypt(byte[] Key, byte[] IV, byte[] cipherText) { if (cipherText == null || cipherText.Length <= 0) { throw new ArgumentNullException("cipherText"); } if (Key == null || Key.Length <= 0) { throw new ArgumentNullException("Key"); } if (IV == null || IV.Length <= 0) { throw new ArgumentNullException("IV"); } BufferedBlockCipher decryptCipher = new BufferedBlockCipher(new CbcBlockCipher(new AesEngine())); decryptCipher.Reset(); ICipherParameters param = new ParametersWithIV(new KeyParameter(Key), IV); decryptCipher.Init(false, param); byte[] buf = new byte[decryptCipher.GetOutputSize(cipherText.Length)]; int len = decryptCipher.ProcessBytes(cipherText, 0, cipherText.Length, buf, 0); len += decryptCipher.DoFinal(buf, len); byte[] plainText = new byte[len]; Array.Copy(buf, 0, plainText, 0, len); return(plainText); }
public byte[] DecryptSessionKey() { //odkodowanie z pliku(klucz = skrot hasla) BufferedBlockCipher aes = new BufferedBlockCipher(new RC6Engine()); aes.Init(true, new KeyParameter(PasswordHash)); var privateKeyEncrypted = File.ReadAllBytes(@"C:\Users\ruchn\OneDrive\Obrazy\Private\" + Username + ".txt"); var privateKey = new byte[aes.GetOutputSize(privateKeyEncrypted.Length)]; var length = aes.ProcessBytes(privateKeyEncrypted, 0, privateKeyEncrypted.Length, privateKey, 0); aes.DoFinal(privateKey, length); var privateKeyToString = Encoding.UTF8.GetString(privateKey); //odkodowanie klucza sesyjnego kluczem prywatnym using (var rsa = new RSACryptoServiceProvider(2048)) { rsa.PersistKeyInCsp = false; try { rsa.FromXmlString(privateKeyToString); return(rsa.Decrypt(EncodedKey, false)); } catch (Exception) { IsPasswordValid = false; return(PasswordHash.Take(KeySize / 8).ToArray()); } } }
private static MemoryStream DecryptAes(Stream inputStream, BufferedBlockCipher cipher, long length) { byte[] input = new byte[length]; byte[] output = new byte[cipher.GetOutputSize((int)length)]; // TODO: Check that all input streams are correctly aligned with the block size. ////int blockSize = cipher.GetBlockSize(); ////long inputLength = inputStream.Length; ////if (inputLength % blockSize > 0) ////{ //// inputLength += blockSize - inputLength % blockSize; ////} ////byte[] input = new byte[inputLength]; ////byte[] output = new byte[cipher.GetOutputSize((int)inputLength)]; inputStream.Read(input, 0, (int)length); int len = cipher.ProcessBytes(input, 0, input.Length, output, 0); cipher.DoFinal(output, len); MemoryStream outputStream = new MemoryStream(); outputStream.Write(output, 0, input.Length); outputStream.Seek(0, SeekOrigin.Begin); return(outputStream); }
private byte[] EncryptBlock( byte[] input, int inOff, int inLen, byte[] z) //throws InvalidCipherTextException { byte[] C = null; KeyParameter macKey = null; KdfParameters kParam = new KdfParameters(z, param.GetDerivationV()); int c_text_length = 0; int macKeySize = param.MacKeySize; if (cipher == null) // stream mode { byte[] Buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8)); C = new byte[inLen + mac.GetMacSize()]; c_text_length = inLen; for (int i = 0; i != inLen; i++) { C[i] = (byte)(input[inOff + i] ^ Buffer[i]); } macKey = new KeyParameter(Buffer, inLen, (macKeySize / 8)); } else { int cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize; byte[] Buffer = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8)); cipher.Init(true, new KeyParameter(Buffer, 0, (cipherKeySize / 8))); c_text_length = cipher.GetOutputSize(inLen); byte[] tmp = new byte[c_text_length]; int len = cipher.ProcessBytes(input, inOff, inLen, C, 0); len += cipher.DoFinal(tmp, len); C = new byte[len + mac.GetMacSize()]; c_text_length = len; Array.Copy(tmp, 0, C, 0, len); macKey = new KeyParameter(Buffer, (cipherKeySize / 8), (macKeySize / 8)); } byte[] macIV = param.GetEncodingV(); mac.Init(macKey); mac.BlockUpdate(C, 0, c_text_length); mac.BlockUpdate(macIV, 0, macIV.Length); // // return the message and it's MAC // mac.DoFinal(C, c_text_length); return(C); }
private byte[] EncryptBlock(byte[] input, int inOff, int inLen, byte[] z) { byte[] c; KeyParameter macKey; var kParam = new KdfParameters(z, _param.Derivation); int cTextLength; var macKeySize = _param.MacKeySize; if (_cipher == null) // stream mode { var buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8)); c = new byte[inLen + _mac.GetMacSize()]; cTextLength = inLen; for (var i = 0; i != inLen; i++) { c[i] = (byte)(input[inOff + i] ^ buffer[i]); } macKey = new KeyParameter(buffer, inLen, (macKeySize / 8)); } else { var cipherKeySize = ((IesWithCipherParameters)_param).CipherKeySize; var buffer = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8)); _cipher.Init(true, new KeyParameter(buffer, 0, (cipherKeySize / 8))); cTextLength = _cipher.GetOutputSize(inLen); var tmp = new byte[cTextLength]; var len = _cipher.ProcessBytes(input, inOff, inLen, tmp, 0); len += _cipher.DoFinal(tmp, len); c = new byte[len + _mac.GetMacSize()]; cTextLength = len; Array.Copy(tmp, 0, c, 0, len); macKey = new KeyParameter(buffer, (cipherKeySize / 8), (macKeySize / 8)); } var macIV = _param.Encoding; _mac.Init(macKey); _mac.BlockUpdate(c, 0, cTextLength); _mac.BlockUpdate(macIV, 0, macIV.Length); // // return the message and it's MAC // _mac.DoFinal(c, cTextLength); return(c); }
public byte[] DecryptDES3(byte[] message, byte[] key) { DesEdeEngine desedeEngine = new DesEdeEngine(); BufferedBlockCipher bufferedCipher = new BufferedBlockCipher(desedeEngine); // Create the KeyParameter for the DES3 key generated. KeyParameter keyparam = ParameterUtilities.CreateKeyParameter("DESEDE", key); byte[] output = new byte[bufferedCipher.GetOutputSize(message.Length)]; bufferedCipher.Init(false, keyparam); output = bufferedCipher.DoFinal(message); return(output); }
public byte[] Decrypt(byte[] key, byte[] iv, byte[] data) { //BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine, new ISO7816d4Padding()); BufferedBlockCipher cipher = new BufferedBlockCipher(engine); //cipher.Init(false, new ParametersWithIV(new DesParameters(key), iv)); cipher.Init(false, new DesEdeParameters(key)); byte[] rv = new byte[cipher.GetOutputSize(data.Length)]; int tam = cipher.ProcessBytes(data, 0, data.Length, rv, 0); cipher.DoFinal(rv, tam); return(rv); }
/// <summary> /// /// </summary> /// <param name="data"></param> /// <param name="key"></param> /// <returns></returns> public static byte[] ComputeCbc3Des(this byte[] data, KeyParameter key) { IBlockCipher engine = new DesEdeEngine(); var cipher = new BufferedBlockCipher(new CbcBlockCipher(engine)); cipher.Init(true, key); var cbc = new byte[cipher.GetOutputSize(data.Length)]; var length = cipher.ProcessBytes(data, 0, data.Length, cbc, 0); cipher.DoFinal(cbc, length); return(cbc); }
public byte[] Decrypt(byte[] value) { BufferedBlockCipher aes = new BufferedBlockCipher(new OfbBlockCipher(new AesEngine(), AesBlockSizeInBytes * 8)); ArraySegment <byte> iv = new ArraySegment <byte>(value, 0, AesBlockSizeInBytes); ArraySegment <byte> secret = new ArraySegment <byte>(value, AesBlockSizeInBytes, value.Length - AesBlockSizeInBytes); ParametersWithIV ivAndKey = new ParametersWithIV(new KeyParameter(aesKey), iv.ToArray()); aes.Init(false, ivAndKey); int maximumSize = aes.GetOutputSize(secret.Count); byte[] outputBuffer = new byte[maximumSize]; int length1 = aes.ProcessBytes(secret.ToArray(), 0, secret.Count, outputBuffer, 0); int length2 = aes.DoFinal(outputBuffer, length1); return(new ArraySegment <byte>(outputBuffer, 0, length1 + length2).ToArray()); }
/* * No idea... doesnt work.. cant seem to fix it.. * * */ private static byte[] Transform(BufferedBlockCipher cipher, byte[] data) { var buf = new byte[cipher.GetOutputSize(data.Length)]; var length = cipher.ProcessBytes(data, 0, data.Length, buf, 0); try { length += cipher.DoFinal(buf, length); } catch (InvalidCipherTextException) { return(null); } var final = new byte[length]; Array.Copy(buf, final, length); return(final); }
private Byte[] Decrypt(BufferedBlockCipher cipher, Byte[] data) { var size = cipher.GetOutputSize(data.Length); var outBuffer = new Byte[size]; //int off1 = cipher.ProcessBytes(content, 0, content.Length, outBuffer, 0); cipher.DoFinal(data, 0, data.Length, outBuffer, 0); //int off2 = cipher.DoFinal(outBuffer, off1); //int resultSize = off1 + off2; var result = new Byte[outBuffer.Length /*resultSize*/]; Array.Copy(outBuffer, 0, result, 0, result.Length); //String asString = Encoding.ASCII.GetString(result); //Console.WriteLine(asString); return(result); }
public static byte[] Encrypt(string key, byte[] inBytes) { var cipher = new BufferedBlockCipher(new BlowfishEngine()); cipher.Init(true, new KeyParameter(Encoding.UTF8.GetBytes(key))); inBytes = BSwap(inBytes); var outBytes = new byte[cipher.GetOutputSize(inBytes.Length)]; var len2 = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); cipher.DoFinal(outBytes, len2); outBytes = BSwap(outBytes); return(outBytes); }
public byte[] Encrypt(byte[] key, byte[] iv, byte[] data) { //BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine, new ISO7816d4Padding()); //BufferedBlockCipher cipher = new BufferedGenericBlockCipher(cipher.getUnderlyingCipher(), new ISO7816d4Padding()); BufferedBlockCipher cipher = new BufferedBlockCipher(engine); //cipher.Init(true, new ParametersWithIV(new DesParameters(key), iv)); cipher.Init(true, new DesEdeParameters(key)); byte[] rv = new byte[cipher.GetOutputSize(data.Length)]; int tam = cipher.ProcessBytes(data, 0, data.Length, rv, 0); cipher.DoFinal(rv, tam); //BufferedBlockCipher bufferedCipher = new BufferedBlockCipher(desedeEngine); // Create the KeyParameter for the DES3 key generated. KeyParameter keyparam = ParameterUtilities.CreateKeyParameter("DESEDE", keyDES3); byte[] output = new byte[bufferedCipher.GetOutputSize(message.Length)]; bufferedCipher.Init(true, keyparam); output = bufferedCipher.DoFinal(message); return(rv); }
private byte[] EncryptBlock(byte[] input, int inOff, int inLen, byte[] z) { byte[] array = null; KeyParameter keyParameter = null; KdfParameters kParam = new KdfParameters(z, param.GetDerivationV()); int num = 0; int macKeySize = param.MacKeySize; if (cipher == null) { byte[] array2 = GenerateKdfBytes(kParam, inLen + macKeySize / 8); array = new byte[inLen + mac.GetMacSize()]; num = inLen; for (int i = 0; i != inLen; i++) { array[i] = (byte)(input[inOff + i] ^ array2[i]); } keyParameter = new KeyParameter(array2, inLen, macKeySize / 8); } else { int cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize; byte[] key = GenerateKdfBytes(kParam, cipherKeySize / 8 + macKeySize / 8); cipher.Init(forEncryption: true, new KeyParameter(key, 0, cipherKeySize / 8)); num = cipher.GetOutputSize(inLen); byte[] array3 = new byte[num]; int num2 = cipher.ProcessBytes(input, inOff, inLen, array3, 0); num2 += cipher.DoFinal(array3, num2); array = new byte[num2 + mac.GetMacSize()]; num = num2; Array.Copy(array3, 0, array, 0, num2); keyParameter = new KeyParameter(key, cipherKeySize / 8, macKeySize / 8); } byte[] encodingV = param.GetEncodingV(); mac.Init(keyParameter); mac.BlockUpdate(array, 0, num); mac.BlockUpdate(encodingV, 0, encodingV.Length); mac.DoFinal(array, num); return(array); }
//this method is used to replace _NewEncryptor method. public byte[] EncryptData(byte[] data, int offset, int length, byte[] key, byte[] iv) { try { var desEngine = new DesEngine(); var cbcBlockCipher = new CbcBlockCipher(desEngine); var bufferedBlockCipher = new BufferedBlockCipher(cbcBlockCipher); bufferedBlockCipher.Init(true, new ParametersWithIV(new KeyParameter(key), iv)); var cipherData = new byte[bufferedBlockCipher.GetOutputSize(length - offset)]; var outputLength = bufferedBlockCipher.ProcessBytes(data, offset, length, cipherData, 0); bufferedBlockCipher.DoFinal(cipherData, outputLength); return(cipherData); } catch (Exception e) { return(null); } }
protected virtual byte[] DecryptBlock( byte[] inEnc, int inOff, int inLen) { byte[] m; byte[] k1, k2; int len = 0; // Ensure that the length of the input is greater than the MAC in bytes if (inLen < (V.Length + Mac.GetMacSize())) { throw new InvalidCipherTextException("Length of input must be greater than the MAC and V combined"); } // note order is important: set up keys, do simple encryptions, check mac, do final encryption. if (Cipher == null) { // Streaming mode. k1 = new byte[inLen - V.Length - Mac.GetMacSize()]; k2 = new byte[_param.MacKeySize / 8]; var k = new byte[k1.Length + k2.Length]; Kdf.GenerateBytes(k, 0, k.Length); if (V.Length != 0) { Array.Copy(k, 0, k2, 0, k2.Length); Array.Copy(k, k2.Length, k1, 0, k1.Length); } else { Array.Copy(k, 0, k1, 0, k1.Length); Array.Copy(k, k1.Length, k2, 0, k2.Length); } // process the message m = new byte[k1.Length]; for (int i = 0; i != k1.Length; i++) { m[i] = (byte)(inEnc[inOff + V.Length + i] ^ k1[i]); } } else { // Block cipher mode. SetupBlockCipherAndMacKeyBytes(out k1, out k2); ICipherParameters cp = new KeyParameter(k1); // If IV provide use it to initialize the cipher if (Iv != null) { cp = new ParametersWithIV(cp, Iv); } Cipher.Init(false, cp); m = new byte[Cipher.GetOutputSize(inLen - V.Length - Mac.GetMacSize())]; // do initial processing len = Cipher.ProcessBytes(inEnc, inOff + V.Length, inLen - V.Length - Mac.GetMacSize(), m, 0); } // Convert the length of the encoding vector into a byte array. byte[] p2 = _param.GetEncodingV(); byte[] l2 = null; if (V.Length != 0) { l2 = GetLengthTag(p2); } // Verify the MAC. int end = inOff + inLen; byte[] t1 = Arrays.CopyOfRange(inEnc, end - Mac.GetMacSize(), end); byte[] t2 = new byte[t1.Length]; Mac.Init(new KeyParameter(k2)); Mac.BlockUpdate(inEnc, inOff + V.Length, inLen - V.Length - t2.Length); SimilarMacCompute(p2, l2, t2); if (!Arrays.ConstantTimeAreEqual(t1, t2)) { throw new InvalidCipherTextException("invalid MAC"); } if (Cipher == null) { return(m); } else { len += Cipher.DoFinal(m, len); return(Arrays.CopyOfRange(m, 0, len)); } }
public override void PerformTest() { char[] password = "******".ToCharArray(); PbeParametersGenerator generator = new Pkcs5S2ParametersGenerator(); EncryptedPrivateKeyInfo info = null; try { info = EncryptedPrivateKeyInfo.GetInstance(Asn1Object.FromByteArray(sample)); } catch (System.Exception e) { Fail("failed construction - exception " + e.ToString(), e); } PbeS2Parameters alg = PbeS2Parameters.GetInstance(info.EncryptionAlgorithm.Parameters); Pbkdf2Params func = Pbkdf2Params.GetInstance(alg.KeyDerivationFunc.Parameters); EncryptionScheme scheme = alg.EncryptionScheme; if (func.KeyLength != null) { keySize = func.KeyLength.IntValue * 8; } int iterationCount = func.IterationCount.IntValue; byte[] salt = func.GetSalt(); generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password), salt, iterationCount); DerObjectIdentifier algOid = scheme.ObjectID; byte[] iv; if (algOid.Equals(PkcsObjectIdentifiers.RC2Cbc)) { RC2CbcParameter rc2Params = RC2CbcParameter.GetInstance(scheme.Asn1Object); iv = rc2Params.GetIV(); } else { iv = ((Asn1OctetString)scheme.Asn1Object).GetOctets(); } ICipherParameters param = new ParametersWithIV( generator.GenerateDerivedParameters(algOid.Id, keySize), iv); cipher.Init(false, param); byte[] data = info.GetEncryptedData(); byte[] outBytes = new byte[cipher.GetOutputSize(data.Length)]; int len = cipher.ProcessBytes(data, 0, data.Length, outBytes, 0); try { len += cipher.DoFinal(outBytes, len); } catch (Exception e) { Fail("failed DoFinal - exception " + e.ToString()); } if (result.Length != len) { Fail("failed length"); } for (int i = 0; i != len; i++) { if (outBytes[i] != result[i]) { Fail("failed comparison"); } } }
/// <summary> /// Export a list of <see cref="SiteParameters"/> to an encrypted export file. Note /// that this method only exports to the newer XML-based cross-platform format, not /// the old platform specific format that is no longer supported. /// </summary> /// <param name="filename">A string containing the full path to the export file</param> /// <param name="password">A string containing the password used to encrypt the /// file</param> /// <param name="generator">A string containing the "generator" ID for the file, usually /// the full application name ("Cryptnos for Windows") and version number. If this /// value is null the generator tag will be omitted from the file.</param> /// <param name="comment">A string containing an optional comment. If this value is /// null the comment tag will be omitted from the file.</param> /// <param name="siteList">A <see cref="List"/> of <see cref="SiteParameters"/> to /// export</param> /// <exception cref="ArgumentException">Thrown if any required field (file name, /// password, or site list) is empty or null</exception> /// <exception cref="Exception">Thrown if anything blows up along the way</exception> public static void ExportToFile(string filename, string password, string generator, string comment, List <SiteParameters> siteList) { try { // A little bit of sanity checking. Make sure our required inputs are // not null or empty: if (String.IsNullOrEmpty(filename)) { throw new ArgumentException("File name is empty or null"); } if (String.IsNullOrEmpty(password)) { throw new ArgumentException("Password is empty or null"); } if (siteList == null || siteList.Count == 0) { throw new ArgumentException("Site parameter list is empty or null"); } // Set up the XML formatting options for our XML writer. I don't think these // guys are actually essential, given that our XML is not meant to be human // readable, but they seemed to work for Mandelbrot Madness! so I'll keep them // here. XmlWriterSettings xws = new XmlWriterSettings(); xws.Indent = true; xws.IndentChars = "\t"; xws.CloseOutput = true; xws.Encoding = Encoding.UTF8; // We won't be writing directly to a file, at least not yet. Create a memory // stream for us to write to initially, then open up the XML writer to point // to that stream. Note that we'll also gzip the XML as it goes into the // memory stream to compress it. MemoryStream ms = new MemoryStream(); XmlWriter xw = XmlWriter.Create(new GZipStream(ms, CompressionMode.Compress), xws); // Start writing out our XML by putting in the required headers. Note that // the <version> tag is required and for now must be 1, but the <generator> // and <comment> tags are technically optional. Generator is highly recommended, // however, as that helps us ID where the file came from. xw.WriteStartDocument(); xw.WriteStartElement("cryptnos", "http://www.cryptnos.com/"); xw.WriteElementString("version", "1"); if (!String.IsNullOrEmpty(generator)) { xw.WriteElementString("generator", generator); } if (!String.IsNullOrEmpty(comment)) { xw.WriteElementString("comment", comment); } xw.WriteElementString("siteCount", siteList.Count.ToString()); // Start writing out the <sites> tag xw.WriteStartElement("sites"); // Now step through each site parameter group and write out a <site> // tag to contain its data: foreach (SiteParameters site in siteList) { xw.WriteStartElement("site"); xw.WriteElementString("siteToken", site.Site); xw.WriteElementString("hash", HashEngine.HashEnumStringToDisplayHash(site.Hash)); xw.WriteElementString("iterations", site.Iterations.ToString()); xw.WriteElementString("charTypes", site.CharTypes.ToString()); if (site.CharLimit < 0) { xw.WriteElementString("charLimit", "0"); } else { xw.WriteElementString("charLimit", site.CharLimit.ToString()); } xw.WriteEndElement(); } // Close the <sites> tag: xw.WriteEndElement(); // Close the <cryptnos> tag and the rest of the document: xw.WriteEndElement(); xw.WriteEndDocument(); xw.Flush(); xw.Close(); ms.Flush(); ms.Close(); // Get the contents of the memory stream as raw bytes: byte[] plaintext = ms.ToArray(); // Create the cipher. Note that we're using the encryption // mode, and that we're passing in the password: BufferedBlockCipher cipher = CreateCipher(password, true); // Create our ciphertext container. Note that we call the // cipher's getOutputSize() method, which tells us how big // the resulting ciphertext should be. In practice, this // has always been the same size as the plaintext, but we // can't take that for granted. byte[] ciphertext = new byte[cipher.GetOutputSize(plaintext.Length)]; // Do the encyrption. Note that the .NET version is different from // the Java version. Here we've got it easy. The BC classes include // a simpler one-call DoFinal() method that does everything for us. ciphertext = cipher.DoFinal(plaintext); // Write the ciphertext to the export file: FileStream fs = new FileStream(filename, FileMode.Create); fs.Write(ciphertext, 0, ciphertext.Length); // Close up shop: fs.Flush(); fs.Close(); plaintext = null; ciphertext = null; } catch (Exception ex) { throw ex; } }
/// <summary> /// Read a <see cref="List"/> of <see cref="SiteParameters"/> from the new XML-based /// cross-platform export file format /// </summary> /// <param name="filename">A string containing the full path to the import file</param> /// <param name="password">A string containing the password used to decrypt the /// file</param> /// <returns>A <see cref="List"/> of <see cref="SiteParameters"/></returns> /// <exception cref="ImportHandlerException">Thrown if a parsing error occurs during /// the import process</exception> /// <exception cref="Exception">Thrown if anything else blows up along the way</exception> private static List <SiteParameters> ImportFromXMLv1File(string filename, string password) { try { // Declare somewhere to hold the site count as read from the file: int siteCount = 0; // Try to open a file stream for the file: FileStream fs = new FileStream(filename, FileMode.Open); // The process below will blow up if we try to read a file that is so large // it exceeds the 32-bit integer max value. This should never happen with an // actual Cryptnos export file, but if the user accidentally tries to import // a DVD ISO or something, we don't want to blow up their machine. Bomb out // if we find out that the file is too large. if (fs.Length > (long)Int32.MaxValue) { fs.Close(); throw new ImportHandlerException("Import file too large to load into memory"); } // Read the entire contents of the file into memory: byte[] contents = new byte[(int)fs.Length]; fs.Read(contents, 0, contents.Length); fs.Close(); // Create our cipher in decryption mode: BufferedBlockCipher cipher = CreateCipher(password, false); // Create our plaintext container: byte[] plaintext = new byte[cipher.GetOutputSize(contents.Length)]; // Decrypt the data and create a memory stream so we can read from it: plaintext = cipher.DoFinal(contents); MemoryStream ms = new MemoryStream(plaintext); contents = null; // Define our XML reader settings: XmlReaderSettings xmlReaderSettings = new XmlReaderSettings(); // Note that we'll point to our local copy of the XSD, which should be in the // application directory: xmlReaderSettings.Schemas.Add("http://www.cryptnos.com/", Application.StartupPath + Char.ToString(System.IO.Path.DirectorySeparatorChar) + "cryptnos_export1.xsd"); // Validate against the schema. Invalid files will throw exceptions: xmlReaderSettings.ValidationType = ValidationType.Schema; xmlReaderSettings.ValidationEventHandler += new ValidationEventHandler(xmlReaderSettings_ValidationEventHandler); // Ignore unnecessary information: xmlReaderSettings.IgnoreComments = true; xmlReaderSettings.IgnoreWhitespace = true; // Close any other file/input streams when we close this one: xmlReaderSettings.CloseInput = true; // Create the XML reader. Note that we're reading from the memory stream // created from the decrypted file, then passing that through a gzip // decompressor before actually getting to the data. XmlReader xr = XmlReader.Create(new GZipStream(ms, CompressionMode.Decompress), xmlReaderSettings); // This forces us to go to the first element, which should be <cryptnos>. If // not, complain: xr.MoveToContent(); if (xr.Name != "cryptnos") { throw new ImportHandlerException("Invalid Cryptnos export file; expected <cryptnos> tag but got <" + xr.Name + ">"); } // At this point, things are looking good. We'll hopefully have sites we can // import now. Go ahead and create our List of SiteParameters so we can start // building it: List <SiteParameters> siteList = new List <SiteParameters>(); // Read the next element. This should be a <version> tag. If it is, make sure // it's a version we recognize. Otherwise, complain. xr.Read(); if (xr.NodeType != XmlNodeType.Element) { throw new ImportHandlerException("Invalid Cryptnos export file; expected an element, but got " + xr.NodeType.ToString()); } if (xr.Name.CompareTo("version") == 0) { xr.Read(); // Make sure this is a text value, then make sure it's the version // number we expect. This version of Cryptnos only accepts version // 1 of the Cryptnos export file format. if (xr.NodeType == XmlNodeType.Text && xr.Value != "1") { throw new ImportHandlerException("This Cryptnos export file appears to have been generated by a later version of Cryptnos and is incompatible with this version. (File format version was " + xr.Value + ".)"); } } else { throw new ImportHandlerException("Invalid Cryptnos export file; expected a <version> element, but got <" + xr.Name + ">"); } // Read on to the next tag: xr.Read(); while (xr.NodeType == XmlNodeType.EndElement) { xr.Read(); } if (xr.NodeType != XmlNodeType.Element) { throw new ImportHandlerException("Invalid Cryptnos export file; expected an element, but got " + xr.NodeType.ToString()); } // At this point, the next few tags should be the <generator> and/or <comment> // tags, neither of which we care about. Therefore, just read ahead until we // hit the <sites> tag, which is where we really want to go to next. while (xr.Name.CompareTo("siteCount") != 0) { do { xr.Read(); } while (xr.NodeType != XmlNodeType.Element); } // The next tag should be the <siteCount> tag. This contains the number of // site blocks in the file. This technically isn't necessary, but it was added // to improve reporting on Android, where performance is much more of an issue. // The main thing we'll worry about here is that (a) it's an integer greater // than zero and (b) the number of sites we eventually read must equal the // count listed here. if (xr.NodeType == XmlNodeType.Element && xr.Name.CompareTo("siteCount") == 0) { xr.Read(); if (xr.NodeType == XmlNodeType.Text) { siteCount = Int32.Parse(xr.Value); } if (siteCount <= 0) { throw new ImportHandlerException("Invalid Cryptnos export file; <siteCount> is " + siteCount.ToString()); } } // Read on to the next tag: xr.Read(); while (xr.NodeType == XmlNodeType.EndElement) { xr.Read(); } // Now we need to check to make sure we actually got a <sites> tag: if (xr.NodeType == XmlNodeType.Element && xr.Name.CompareTo("sites") == 0) { // Read the next tag. This should be a <site> tag and the beginning of a // site defintion. xr.Read(); while (xr.NodeType == XmlNodeType.Element && xr.Name.CompareTo("site") == 0) { // Create a new SiteParameters object to store the data we're about // to read. SiteParameters site = new SiteParameters(); // Try to read the <siteToken> tag: xr.Read(); if (xr.NodeType != XmlNodeType.Element) { throw new ImportHandlerException("Invalid Cryptnos export file; expected an element, but got " + xr.NodeType.ToString()); } if (xr.Name.CompareTo("siteToken") == 0) { xr.Read(); if (xr.NodeType == XmlNodeType.Text) { site.Site = xr.Value; } else { throw new ImportHandlerException("Invalid site token (" + xr.Value + ")"); } } else { throw new ImportHandlerException("Invalid Cryptnos export file; expected a <siteToken> element, but got <" + xr.Name + ">"); } do { xr.Read(); } while (xr.NodeType != XmlNodeType.Element); // Try to read the <hash> tag: if (xr.NodeType != XmlNodeType.Element) { throw new ImportHandlerException("Invalid Cryptnos export file; expected an element, but got " + xr.NodeType.ToString()); } if (xr.Name.CompareTo("hash") == 0) { xr.Read(); if (xr.NodeType == XmlNodeType.Text) { site.Hash = HashEngine.DisplayHashToHashEnumString(xr.Value); } else { throw new ImportHandlerException("Invalid hash token (" + xr.Value + ")"); } } else { throw new ImportHandlerException("Invalid Cryptnos export file; expected a <hash> element, but got <" + xr.Name + ">"); } do { xr.Read(); } while (xr.NodeType != XmlNodeType.Element); // Try to read the <iterations> tag: if (xr.NodeType != XmlNodeType.Element) { throw new ImportHandlerException("Invalid Cryptnos export file; expected an element, but got " + xr.NodeType.ToString()); } if (xr.Name.CompareTo("iterations") == 0) { xr.Read(); if (xr.NodeType == XmlNodeType.Text) { site.Iterations = Int32.Parse(xr.Value); } else { throw new ImportHandlerException("Invalid iterations token (" + xr.Value + ")"); } } else { throw new ImportHandlerException("Invalid Cryptnos export file; expected an <iterations> element, but got <" + xr.Name + ">"); } do { xr.Read(); } while (xr.NodeType != XmlNodeType.Element); // Try to read the <charTypes> tag: if (xr.NodeType != XmlNodeType.Element) { throw new ImportHandlerException("Invalid Cryptnos export file; expected an element, but got " + xr.NodeType.ToString()); } if (xr.Name.CompareTo("charTypes") == 0) { xr.Read(); if (xr.NodeType == XmlNodeType.Text) { site.CharTypes = Int32.Parse(xr.Value); } else { throw new ImportHandlerException("Invalid charTypes token (" + xr.Value + ")"); } } else { throw new ImportHandlerException("Invalid Cryptnos export file; expected a <charTypes> element, but got <" + xr.Name + ">"); } do { xr.Read(); } while (xr.NodeType != XmlNodeType.Element); // Try to read the <charLimit> tag: if (xr.NodeType != XmlNodeType.Element) { throw new ImportHandlerException("Invalid Cryptnos export file; expected an element, but got " + xr.NodeType.ToString()); } if (xr.Name.CompareTo("charLimit") == 0) { xr.Read(); if (xr.NodeType == XmlNodeType.Text) { // The character limit, unfortunately, is a bit inconsistent. // Obviously, we can't limit it to zero, as that will mean we // have an empty password. But the XML schema defines this as // only positive integers, so our built-in -1 value can't work. // So if we read a zero, convert it to -1 here. We'll do the // reverse when we write the file. site.CharLimit = Int32.Parse(xr.Value); if (site.CharLimit == 0) { site.CharLimit = -1; } } else { throw new ImportHandlerException("Invalid charLimit token (" + xr.Value + ")"); } } else { throw new ImportHandlerException("Invalid Cryptnos export file; expected a <charLimit> element, but got <" + xr.Name + ">"); } // The next item should be the closing element for <charLimit>, so // read it in and then read the next one. That should either be the // start element for the next <site> or the closing element for // <sites>. xr.Read(); if (xr.NodeType == XmlNodeType.EndElement) { xr.Read(); } else { throw new ImportHandlerException("Invalid Cryptnos export file; expected ending <charLimit> tag, got " + xr.NodeType.ToString()); } if (xr.NodeType == XmlNodeType.EndElement) { xr.Read(); } else { throw new ImportHandlerException("Invalid Cryptnos export file; expected ending <site> tag, got " + xr.NodeType.ToString()); } // We should now have a hopefully valid SiteParameters object. Add it // to the site list: siteList.Add(site); } // We get here, we've exhausted the <sites> block and all that should be // left will be closing tags. If we were going to be extremely thorough, // we should probably check these closing tags and make sure they're legit. // For now, we'll just assume there's nothing left to read. Close the // streams, free up memory, and return the list of read sites. xr.Close(); ms.Close(); ms.Dispose(); plaintext = null; if (siteList.Count != siteCount) { throw new ImportHandlerException("Invalid Cryptnos export file; File reported " + siteCount.ToString() + " sites in the file, but actually read " + siteList.Count.ToString()); } return(siteList); } else { throw new ImportHandlerException("Invalid Cryptnos export file; could not find <sites> tag"); } } catch (Exception ex) { throw ex; } }
public void Execute() { int keysize; switch (_settings.Keysize) { case 1: keysize = 24; break; case 2: keysize = 32; break; default: keysize = 16; break; } if (InputKey.Length != keysize) { GuiLogMessage(String.Format("Wrong keysize given. Keysize was {0} Bits but needed is {1} Bits.", InputKey.Length * 8, keysize * 8), NotificationLevel.Error); return; } if (InputIV == null) { if (_settings.Mode > 0) { GuiLogMessage("NOTE: No IV provided. Using 0x000..00!", NotificationLevel.Info); } InputIV = new byte[16]; } if (InputIV.Length < 16 && _settings.Mode > 0) { GuiLogMessage(String.Format("NOTE: Wrong IV size given. IV size was {0} Bits but needed is 128 Bits. Appending with zeros.", InputIV.Length * 8), NotificationLevel.Info); var newIV = new byte[16]; Array.Copy(InputIV, 0, newIV, 0, InputIV.Length); InputIV = newIV; } else if (InputIV.Length > 16 && _settings.Mode > 0) { GuiLogMessage(String.Format("NOTE: Wrong IV size given. IV size was {0} Bits but needed is 128 Bits. Removing bytes from position 15.", InputIV.Length * 8), NotificationLevel.Info); var newIV = new byte[16]; Array.Copy(InputIV, 0, newIV, 0, 16); InputIV = newIV; } var keyParameter = new KeyParameter(InputKey); var engine = new CamelliaEngine(); var keyParameterWithIv = new ParametersWithIV(keyParameter, InputIV); BufferedBlockCipher cipher; switch (_settings.Mode) { case 1: cipher = new BufferedBlockCipher(new CbcBlockCipher(engine)); break; case 2: cipher = new BufferedBlockCipher(new CfbBlockCipher(engine, 128)); break; case 3: cipher = new BufferedBlockCipher(new OfbBlockCipher(engine, 128)); break; default: cipher = new BufferedBlockCipher(engine); break; } if (_settings.Mode > 0) { cipher.Init(_settings.Action == 0, keyParameterWithIv); } else { cipher.Init(_settings.Action == 0, keyParameter); } //Add padding if (_settings.Action == 0 && _settings.Padding > 0) { var paddingType = BlockCipherHelper.PaddingType.None; switch (_settings.Padding) { case 1: paddingType = BlockCipherHelper.PaddingType.Zeros; break; case 2: paddingType = BlockCipherHelper.PaddingType.PKCS7; break; case 3: paddingType = BlockCipherHelper.PaddingType.ANSIX923; break; case 4: paddingType = BlockCipherHelper.PaddingType.ISO10126; break; case 5: paddingType = BlockCipherHelper.PaddingType.OneZeros; break; } InputStream = BlockCipherHelper.AppendPadding(InputStream, paddingType, 16); } var inputText = InputStream.CreateReader().ReadFully(); var outputText = new byte[cipher.GetOutputSize(inputText.Length)]; var outputLen = cipher.ProcessBytes(inputText, 0, inputText.Length, outputText, 0); cipher.DoFinal(outputText, outputLen); OutputStream = new CStreamWriter(); int offset = outputText.Length; //Remove the padding from the output if (_settings.Action == 1 && _settings.Padding > 0) { var paddingType = BlockCipherHelper.PaddingType.None; switch (_settings.Padding) { case 1: paddingType = BlockCipherHelper.PaddingType.Zeros; break; case 2: paddingType = BlockCipherHelper.PaddingType.PKCS7; break; case 3: paddingType = BlockCipherHelper.PaddingType.ANSIX923; break; case 4: paddingType = BlockCipherHelper.PaddingType.ISO10126; break; case 5: paddingType = BlockCipherHelper.PaddingType.OneZeros; break; } offset = BlockCipherHelper.StripPadding(outputText, outputText.Length - outputText.Length % 16, paddingType, outputText.Length); } //Output encrypted or decrypted text ((CStreamWriter)OutputStream).Write(outputText, 0, offset); ((CStreamWriter)OutputStream).Close(); OnPropertyChanged("OutputStream"); }
public string DoEncrypt(string symmetricBlockAlgorithm, string symmetricBlockMode, string symmetricBlockPadding, string key, string IV, string plainText) { this.error.cleanError(); SymmetricBlockAlgorithm algorithm = SymmetricBlockAlgorithmUtils.getSymmetricBlockAlgorithm(symmetricBlockAlgorithm, this.error); SymmetricBlockMode mode = SymmetricBlockModeUtils.getSymmetricBlockMode(symmetricBlockMode, this.error); SymmetricBlockPadding padding = SymmetricBlockPaddingUtils.getSymmetricBlockPadding(symmetricBlockPadding, this.error); if (this.error.existsError()) { return(""); } BufferedBlockCipher bbc = getCipher(algorithm, mode, padding); if (this.error.existsError() && !(string.Compare(this.error.Code, "SB016", true) == 0)) { return(""); } byte[] byteIV = SecurityUtils.GetHexa(IV, "SB022", this.error); byte[] byteKey = SecurityUtils.GetHexa(key, "SB022", this.error); if (this.HasError()) { return(""); } KeyParameter keyParam = new KeyParameter(byteKey); if (SymmetricBlockMode.ECB != mode && SymmetricBlockMode.OPENPGPCFB != mode) { ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, byteIV); try{ bbc.Init(true, keyParamWithIV); }catch (Exception e) { this.error.setError("SB025", e.Message); return(""); } } else { try { bbc.Init(true, keyParam); }catch (Exception e) { this.error.setError("SB026", e.Message); return(""); } } EncodingUtil eu = new EncodingUtil(); byte[] inputBytes = eu.getBytes(plainText); if (eu.GetError().existsError()) { this.error = eu.GetError(); return(""); } byte[] outputBytes = new byte[bbc.GetOutputSize(inputBytes.Length)]; int length = bbc.ProcessBytes(inputBytes, 0, inputBytes.Length, outputBytes, 0); try { bbc.DoFinal(outputBytes, length); } catch (Exception) { this.error.setError("SB013", "Block encryption exception"); return(""); } string result = Base64.ToBase64String(outputBytes); if (result == null || result.Length == 0) { this.error.setError("SB014", "Error encoding base64"); return(""); } this.error.cleanError(); return(result); }
public string DoDecrypt(string symmetricBlockAlgorithm, string symmetricBlockMode, string symmetricBlockPadding, string key, string IV, string encryptedInput) { this.error.cleanError(); SymmetricBlockAlgorithm algorithm = SymmetricBlockAlgorithmUtils.getSymmetricBlockAlgorithm(symmetricBlockAlgorithm, this.error); SymmetricBlockMode mode = SymmetricBlockModeUtils.getSymmetricBlockMode(symmetricBlockMode, this.error); SymmetricBlockPadding padding = SymmetricBlockPaddingUtils.getSymmetricBlockPadding(symmetricBlockPadding, this.error); if (this.error.existsError()) { return(""); } BufferedBlockCipher bbc = getCipher(algorithm, mode, padding); if (this.error.existsError() && !(string.Compare(this.error.Code, "SB016", true) == 0)) { return(""); } byte[] bytesKey = SecurityUtils.GetHexa(key, "SB023", this.error); byte[] bytesIV = SecurityUtils.GetHexa(IV, "SB023", this.error); if (this.HasError()) { return(""); } KeyParameter keyParam = new KeyParameter(bytesKey); if (SymmetricBlockMode.ECB != mode && SymmetricBlockMode.OPENPGPCFB != mode) { ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, bytesIV); try { bbc.Init(false, keyParamWithIV); }catch (Exception e) { this.error.setError("SB027", e.Message); return(""); } } else { try { bbc.Init(false, keyParam); }catch (Exception e) { this.error.setError("SB028", e.Message); return(""); } } byte[] out2 = Base64.Decode(encryptedInput); byte[] comparisonBytes = new byte[bbc.GetOutputSize(out2.Length)]; int length = bbc.ProcessBytes(out2, 0, out2.Length, comparisonBytes, 0); try { bbc.DoFinal(comparisonBytes, length); } catch (Exception) { this.error.setError("SB015", "Block decryption exception"); return(""); } this.error.cleanError(); EncodingUtil eu = new EncodingUtil(); this.error = eu.GetError(); return(eu.getString(comparisonBytes)); }