private byte[] DecryptManaged(byte[] Key, byte[] Vector, byte[] Data, PaddingMode Padding = PaddingMode.Zeros) { byte[] decryptedBytes; int count = 0; using (MemoryStream stream = new MemoryStream(Data)) { using (RijndaelManaged cipher = new RijndaelManaged()) { cipher.Mode = CipherMode.CBC; cipher.Padding = Padding; cipher.KeySize = Key.Length * 8; cipher.BlockSize = Vector.Length * 8; using (ICryptoTransform decryptor = cipher.CreateDecryptor(Key, Vector)) { using (CryptoStream reader = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { decryptedBytes = new byte[stream.Length]; count = reader.Read(decryptedBytes, 0, decryptedBytes.Length); } } cipher.Clear(); } } return decryptedBytes; }
// Decrypt a byte array into a byte array using a key and an IV public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV, CipherMode cipherMode, PaddingMode paddingMode) { // Create a MemoryStream that is going to accept the // decrypted bytes MemoryStream ms = new MemoryStream(); // Create a symmetric algorithm. // We are going to use Rijndael because it is strong and // available on all platforms. // You can use other algorithms, to do so substitute the next // line with something like // TripleDES alg = TripleDES.Create(); Rijndael alg = Rijndael.Create(); // Now set the key and the IV. // We need the IV (Initialization Vector) because the algorithm // is operating in its default // mode called CBC (Cipher Block Chaining). The IV is XORed with // the first block (8 byte) // of the data after it is decrypted, and then each decrypted // block is XORed with the previous // cipher block. This is done to make encryption more secure. // There is also a mode called ECB which does not need an IV, // but it is much less secure. alg.Mode = cipherMode; alg.Padding = paddingMode; alg.Key = Key; alg.IV = IV; // Create a CryptoStream through which we are going to be // pumping our data. // CryptoStreamMode.Write means that we are going to be // writing data to the stream // and the output will be written in the MemoryStream // we have provided. CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write); // Write the data and make it do the decryption cs.Write(cipherData, 0, cipherData.Length); // Close the crypto stream (or do FlushFinalBlock). // This will tell it that we have done our decryption // and there is no more data coming in, // and it is now a good time to remove the padding // and finalize the decryption process. cs.Close(); // Now get the decrypted data from the MemoryStream. // Some people make a mistake of using GetBuffer() here, // which is not the right way. byte[] decryptedData = ms.ToArray(); return decryptedData; }
public String EncryptIt(String s, byte[] key = null, byte[] IV = null, PaddingMode padding = PaddingMode.PKCS7) { String result; //magically assign key and IV if one isn't given as an argument key = key ?? cryptKey; IV = IV ?? cryptIV; RijndaelManaged rijn = new RijndaelManaged(); rijn.Mode = CipherMode.CBC; rijn.Padding = padding; rijn.BlockSize = 256; using (MemoryStream msEncrypt = new MemoryStream()) { using (ICryptoTransform encryptor = rijn.CreateEncryptor(key, IV)) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(s); } } } result = Convert.ToBase64String(msEncrypt.ToArray()); } rijn.Clear(); return result; }
private void buttonGenerator_Click(object sender, EventArgs e) { try { // Selected 'Preset' if (tabControl.SelectedIndex == 0) { CurrentBlockSize = comboBoxPresets.SelectedIndex == 0 ? 128 : 256; CurrentKeySize = comboBoxPresets.SelectedIndex == 0 ? 128 : 256; SelectedCipher = CipherMode.CBC; SelectedPadding = PaddingMode.PKCS7; } int index = tabControl.SelectedIndex; if ((index == 0 && comboBoxPresets.SelectedIndex == 1) || (index == 1 && radioButtonAes.Checked)) Build(new RijndaelManaged()); else Build(new AesManaged()); } catch (Exception ex) { MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static byte[] Decrypt(byte[] value, byte[] key, byte[] iv, CipherMode mode = CipherMode.CBC, PaddingMode padding = PaddingMode.None) { if (value == null || value.Length <= 0) throw new ArgumentNullException("value"); if (key == null || key.Length <= 0) throw new ArgumentNullException("key"); if (iv == null || iv.Length <= 0) throw new ArgumentNullException("iv"); byte[] result; using (RijndaelManaged rijndael = new RijndaelManaged()) { rijndael.Key = key; rijndael.IV = iv; rijndael.Mode = mode; rijndael.Padding = padding; ICryptoTransform transform = rijndael.CreateDecryptor(rijndael.Key, rijndael.IV); using (MemoryStream memory = new MemoryStream()) using (CryptoStream crypto = new CryptoStream(memory, transform, CryptoStreamMode.Read)) { crypto.Write(value, 0, value.Length); result = memory.ToArray(); } } return result; }
public static ICryptoTransform Create(PaddingMode paddingMode, BasicSymmetricCipher cipher, bool encrypting) { if (encrypting) return new UniversalCryptoEncryptor(paddingMode, cipher); else return new UniversalCryptoDecryptor(paddingMode, cipher); }
public SymmetricKey(SymmetricAlgorithmType type, byte[] iv, byte[] key, CipherModePlus cipherMode, PaddingMode paddingMode, bool enableIVShuffle) { _type = type; switch (type) { case SymmetricAlgorithmType.None: _algo = null; return; case SymmetricAlgorithmType.Camellia: _algo = new openCrypto.CamelliaManaged (); break; case SymmetricAlgorithmType.Rijndael: _algo = new openCrypto.RijndaelManaged (); break; default: throw new ArgumentOutOfRangeException (); } _algo.ModePlus = cipherMode; _algo.Padding = paddingMode; _algo.KeySize = key.Length << 3; _algo.BlockSize = iv.Length << 3; _algo.FeedbackSize = iv.Length << 3; _iv = iv; _key = key; _ivShuffle = enableIVShuffle; }
public static byte[] ApplyPadding(PaddingMode mode, byte[] bytes, int blockSizeInBytes) { int paddingBytesNeeded = GetPaddingBytesNeeded(mode, bytes.Length, blockSizeInBytes); if (paddingBytesNeeded == 0) { // sanity check return ByteUtilities.Clone(bytes); } byte[] output = new byte[blockSizeInBytes]; Buffer.BlockCopy(bytes, 0, output, 0, bytes.Length); switch (mode) { case PaddingMode.ANSIX923: ApplyAnsiX923Padding(output, paddingBytesNeeded); break; case PaddingMode.ISO10126: ApplyIso10126Padding(output, paddingBytesNeeded); break; case PaddingMode.PKCS7: ApplyPkcs7Padding(output, paddingBytesNeeded); break; case PaddingMode.Zeros: // nop break; default: throw new NotImplementedException("Padding mode not implemented"); } return output; }
public String DecryptIt(String s, byte[] key = null, byte[] IV = null, PaddingMode padding = PaddingMode.PKCS7) { String result; //magically assign key and IV if one isn't given as an argument key = key ?? cryptKey; IV = IV ?? cryptIV; RijndaelManaged rijn = new RijndaelManaged(); rijn.Mode = CipherMode.CBC; rijn.Padding = padding; rijn.BlockSize = 256; using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(s))) { using (ICryptoTransform decryptor = rijn.CreateDecryptor(key, IV)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader swDecrypt = new StreamReader(csDecrypt)) { result = swDecrypt.ReadToEnd(); } } } } rijn.Clear(); return result; }
public static string Decrypt(EncryptionAlgorithm algorithm, CiphertextFormat format, string data, Key key, byte[] salt, byte[] iv, PaddingMode paddingMode) { var _d = new byte[0]; switch (format) { case CiphertextFormat.Base64: { _d = Convert.FromBase64String(data); break; } case CiphertextFormat.Hex: { _d = HexToByteArray(data); break; } case CiphertextFormat.Url: { var encoding = new UTF8Encoding(); _d = encoding.GetBytes(HttpUtility.UrlDecode(data)); break; } } return Decrypt(algorithm, _d, key, salt, iv, paddingMode); }
private static void ValidatePaddingMode_NonISO10126(PaddingMode paddingMode, int expectedPaddingSize, string plainTextStr, string expectedCipherStr) { Assert.True(paddingMode != PaddingMode.ISO10126, "This tests only non-ISO10126 padding"); byte[] key = "1ed2f625c187b993256a8b3ccf9dcbfa5b44b4795c731012f70e4e64732efd5d".HexToByteArray(); byte[] iv = "47d1e060ba3c8643f9f8b65feeda4b30".HexToByteArray(); byte[] plainText = plainTextStr.HexToByteArray(); byte[] expectedCipher = expectedCipherStr == null ? Array.Empty<byte>() : expectedCipherStr.HexToByteArray(); using (Aes a = Aes.Create()) { a.Key = key; a.IV = iv; a.Mode = CipherMode.CBC; a.Padding = paddingMode; byte[] cipher = a.Encrypt(plainText); Assert.Equal(expectedCipherStr, cipher.ByteArrayToHex()); // decrypt it with PaddingMode.None so that we can inspect the padding manually a.Padding = PaddingMode.None; byte[] decrypted = a.Decrypt(cipher); ValidatePadding(decrypted, paddingMode, expectedPaddingSize); } }
public static string Decrypt(string cipherText, string Password, CipherMode cipherMode, PaddingMode paddingMode) { byte[] cipherData = Convert.FromBase64String(cipherText); PasswordDeriveBytes bytes = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 110, 0x20, 0x4d, 0x65, 100, 0x76, 0x65, 100, 0x65, 0x76 }); byte[] buffer2 = Decrypt(cipherData, bytes.GetBytes(0x20), bytes.GetBytes(0x10), cipherMode, paddingMode); return Encoding.Unicode.GetString(buffer2); }
public SymmetricTransform (SymmetricAlgorithm symmAlgo, bool encryption, byte[] rgbIV) { algo = symmAlgo; encrypt = encryption; BlockSizeByte = (algo.BlockSize >> 3); if (rgbIV == null) { rgbIV = KeyBuilder.IV (BlockSizeByte); } else { rgbIV = (byte[]) rgbIV.Clone (); } // compare the IV length with the "currently selected" block size and *ignore* IV that are too big if (rgbIV.Length < BlockSizeByte) { string msg = Locale.GetText ("IV is too small ({0} bytes), it should be {1} bytes long.", rgbIV.Length, BlockSizeByte); throw new CryptographicException (msg); } padmode = algo.Padding; // mode buffers temp = new byte [BlockSizeByte]; Buffer.BlockCopy (rgbIV, 0, temp, 0, System.Math.Min (BlockSizeByte, rgbIV.Length)); temp2 = new byte [BlockSizeByte]; #if !MOONLIGHT FeedBackByte = (algo.FeedbackSize >> 3); #endif // transform buffers workBuff = new byte [BlockSizeByte]; workout = new byte [BlockSizeByte]; }
/// <summary> /// Decrypts a byte array with a password /// </summary> /// <param name="data">Data to decrypt</param> /// <param name="password">Password to use</param> /// <param name="paddingMode">Padding mode to use</param> /// <returns>Decrypted byte array</returns> /// <exception cref="System.ArgumentNullException"> /// data /// or /// password /// </exception> /// <exception cref="ArgumentNullException"></exception> public static byte[] DecryptData(byte[] data, string password, PaddingMode paddingMode) { if (data == null || data.Length == 0) throw new ArgumentNullException("data"); if (password == null) throw new ArgumentNullException("password"); var pdb = new PasswordDeriveBytes(password, Encoding.UTF8.GetBytes("Salt")); var rm = new RijndaelManaged { Padding = paddingMode }; ICryptoTransform decryptor = rm.CreateDecryptor(pdb.GetBytes(16), pdb.GetBytes(16)); pdb.Dispose(); using (var msDecrypt = new MemoryStream(data)) using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { // Decrypted bytes will always be less then encrypted bytes, so length of encrypted data will be big enough for buffer. byte[] fromEncrypt = new byte[data.Length]; // Read as many bytes as possible. int read = csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); if (read < fromEncrypt.Length) { // Return a byte array of proper size. byte[] clearBytes = new byte[read]; Buffer.BlockCopy(fromEncrypt, 0, clearBytes, 0, read); return clearBytes; } return fromEncrypt; } }
private static ICryptoTransform CreateTransformCore( CipherMode cipherMode, PaddingMode paddingMode, byte[] key, byte[] iv, int blockSize, bool encrypting) { // The algorithm pointer is a static pointer, so not having any cleanup code is correct. IntPtr algorithm; switch (cipherMode) { case CipherMode.CBC: algorithm = Interop.Crypto.EvpDesCbc(); break; case CipherMode.ECB: algorithm = Interop.Crypto.EvpDesEcb(); break; default: throw new NotSupportedException(); } BasicSymmetricCipher cipher = new OpenSslCipher(algorithm, cipherMode, blockSize, key, 0, iv, encrypting); return UniversalCryptoTransform.Create(paddingMode, cipher, encrypting); }
private byte[] Encrypt (SymmetricAlgorithm algo, PaddingMode padding, byte[] data) { algo.IV = new byte [algo.BlockSize >> 3]; algo.Mode = CipherMode.CBC; algo.Padding = padding; ICryptoTransform ct = algo.CreateEncryptor (); return ct.TransformFinalBlock (data, 0, data.Length); }
public CapiSymmetricAlgorithm(int blockSize, int feedbackSize, SafeCspHandle provider, SafeCapiKeyHandle key, byte[] iv, CipherMode cipherMode, PaddingMode paddingMode, EncryptionMode encryptionMode) { this.m_blockSize = blockSize; this.m_encryptionMode = encryptionMode; this.m_paddingMode = paddingMode; this.m_provider = provider.Duplicate(); this.m_key = SetupKey(key, ProcessIV(iv, blockSize, cipherMode), cipherMode, feedbackSize); }
public RijndaelDecryptionCfbTransform(Rijndael rijndael, int feedbackSizeInBits, byte[] initializationVector, PaddingMode paddingMode) : base(rijndael, paddingMode) { _FeedbackSizeInBytes = feedbackSizeInBits/Constants.BitsPerByte; _FeedbackIterations = rijndael.BlockSize/feedbackSizeInBits; _LastVector = ByteUtilities.Clone(initializationVector); }
/// <summary> /// Initializes a new instance of the SymmetricAlgorithm class. /// </summary> /// <param name="session">The cryptoki session context for which the symmectric algorithm will execute.</param> /// <param name="ownsSession">true if the session should be closed by this base class, false otherwise.</param> protected SymmetricAlgorithm(Session session, bool ownsSession) : base(session, ownsSession) { // Default to cipher block chaining (CipherMode.CBC) and // PKCS-style padding (pad n bytes with value n) ModeValue = CipherMode.CBC; PaddingValue = PaddingMode.PKCS7; }
private static ICryptoTransform CreateDecryptor( CipherMode cipherMode, PaddingMode paddingMode, byte[] key, byte[] iv, int blockSize) { return new AesCngCryptoDecryptor(cipherMode, paddingMode, key, iv, blockSize); }
private static ICryptoTransform CreateEncryptor( CipherMode cipherMode, PaddingMode paddingMode, byte[] key, byte[] iv, int blockSize) { return new AesOpenSslCryptoTransform(cipherMode, paddingMode, key, iv, blockSize, true); }
public HwAes(Connection connection, byte[] Key, int KeySize, CipherMode cipherMode, PaddingMode padding) { this.AES = new AesCryptoServiceProvider(); this.AES.Padding = padding; this.AES.Mode = cipherMode; this.AES.KeySize = KeySize; this.IvConfuser = new DataConfuser(connection.PrivateSeed, 16); ApplyKey(Key); }
public static int GetPaddingBytesNeeded(PaddingMode mode, int byteLength, int blockSizeInBytes) { if (mode == PaddingMode.None) { return 0; } return blockSizeInBytes - byteLength; }
/// <summary> /// Costruttore della classe per crittografare /// </summary> public Encryption(string strSalt = "") { keySize = 32; // 32 caratteri (256 bit) blockSize = 32; // 32 caratteri (256 bit) paddingMode = PaddingMode.PKCS7; // Completa con numero progressivo cipherMode = CipherMode.CBC; // Combina blocco precedente crittografato al successivo (contro blocchi identici) IVbase64size = IVbase64length(); // Imposta la lunghezza dell'IV in base64 errors = new List<string>(); // Lista dei messaggi di errore o altro SetSalt(strSalt); }
public static RijndaelManaged getAESECBCipher(byte[] keyBytes, PaddingMode padding) { RijndaelManaged cipher = new RijndaelManaged(); cipher.KeySize = 128; cipher.BlockSize = 128; cipher.Mode = CipherMode.ECB; cipher.Padding = padding; cipher.Key = keyBytes; return cipher; }
public RijndaelParameters(RijndaelManaged rijndael) { BlockSize = rijndael.BlockSize; FeedbackSize = rijndael.FeedbackSize; KeySize = rijndael.KeySize; Mode = rijndael.Mode; Padding = rijndael.Padding; IV = rijndael.IV; Key = rijndael.Key; }
public EncryptedXml(XmlDocument document, Evidence evidence) { this.m_document = document; this.m_evidence = evidence; this.m_xmlResolver = null; this.m_padding = PaddingMode.ISO10126; this.m_mode = CipherMode.CBC; this.m_encoding = System.Text.Encoding.UTF8; this.m_keyNameMapping = new Hashtable(4); }
/// <summary> /// Initializes a new instance of the RijndaelUnmanagedTransform class. /// </summary> /// <param name="algorithm">One of the <see cref="CryptoAlgorithm"/> values.</param> /// <param name="method">One of the <see cref="CryptoMethod"/> values.</param> /// <param name="key">The key to use.</param> /// <param name="iv">The IV to use.</param> /// <param name="mode">One of the <see cref="CipherMode"/> values.</param> /// <param name="feedback">The feedback size of the cryptographic operation in bits.</param> /// <param name="padding">One of the <see cref="PaddingMode"/> values.</param> public RijndaelUnmanagedTransform(CryptoAlgorithm algorithm, CryptoMethod method, byte[] key, byte[] iv, CipherMode mode, int feedback, PaddingMode padding) { m_Key = new SymmetricKey(CryptoProvider.RsaAes, algorithm, key); m_Key.IV = iv; m_Key.Mode = mode; if (mode == CipherMode.CFB) m_Key.FeedbackSize = feedback; m_Key.Padding = padding; m_BlockSize = 128; m_Method = method; }
public TripleDesSymmetricKeyCryptoProvider(string base64EncodedKey, CipherMode cipherMode, PaddingMode paddingMode) { var tripleDes = TripleDES.Create(); tripleDes.Mode = cipherMode; tripleDes.Padding = paddingMode; tripleDes.Key = Convert.FromBase64String(base64EncodedKey); _encrypt = tripleDes.CreateEncryptor(); _decrypt = tripleDes.CreateDecryptor(); }
/// <summary> /// Run a round trip test -- the data should encrypt and decrypt back to itself /// </summary> /// <param name="key">key to use</param> /// <param name="iv">IV to use</param> /// <param name="text">data to encrypt</param> /// <param name="padding">padding method to use</param> /// <returns>true if text encrypted and decrypted back to itself</returns> protected bool RunRoundTrip(Session session, byte[] key, byte[] iv, byte[] text, PaddingMode padding) { try { Log.Comment("Encrypting the following bytes:"); PrintByteArray(text); // setup the encryption provider AesCryptoServiceProvider aes = new AesCryptoServiceProvider(CryptoKey.ImportKey(session, key, CryptoKey.KeyClass.Secret, CryptoKey.KeyType.AES, true)); aes.IV = iv; aes.Mode = CipherMode.ECB; aes.Padding = padding; // encrypt the data ICryptoTransform sse = aes.CreateEncryptor(); //MemoryStream ms = new MemoryStream(); //CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write); //cs.Write(text, 0, text.Length); //cs.FlushFinalBlock(); byte[] cipherText = sse.TransformFinalBlock(text, 0, text.Length); //ms.ToArray(); //cs.Close(); Log.Comment("Cyphertext:"); PrintByteArray(cipherText); Log.Comment("Decrypting..."); ICryptoTransform ssd = aes.CreateDecryptor(); //cs = new CryptoStream(new MemoryStream(cipherText), ssd, CryptoStreamMode.Read); // decrypt the data byte[] newPlainText = ssd.TransformFinalBlock(cipherText, 0, cipherText.Length); // new byte[text.Length]; //cs.Read(newPlainText, 0, text.Length); Log.Comment("Plaintext:"); PrintByteArray(newPlainText); // make sure the roundtrip worked if (!Compare(text, newPlainText)) { Log.Comment("ERROR: roundtrip failed"); return false; } } catch (NotSupportedException) { throw; } catch { return false; } return true; }
/// <summary>对称加密算法扩展</summary> /// <param name="sa">算法</param> /// <param name="data">数据</param> /// <param name="pass">密码</param> /// <param name="mode">模式。.Net默认CBC,Java默认ECB</param> /// <param name="padding">填充算法。默认PKCS7,等同Java的PKCS5</param> /// <returns></returns> public static Byte[] Encrypt(this SymmetricAlgorithm sa, Byte[] data, Byte[] pass = null, CipherMode mode = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) { if (data == null || data.Length < 1) { throw new ArgumentNullException(nameof(data)); } if (pass != null && pass.Length > 0) { var keySize = sa.KeySize / 8; sa.Key = Pad(pass, keySize); var ivSize = sa.IV.Length; sa.IV = Pad(pass, ivSize); sa.Mode = mode; sa.Padding = padding; } var outstream = new MemoryStream(); using var stream = new CryptoStream(outstream, sa.CreateEncryptor(), CryptoStreamMode.Write); stream.Write(data, 0, data.Length); // 数据长度必须是8的倍数 if (sa.Padding == PaddingMode.None) { var len = data.Length % 8; if (len > 0) { var buf = new Byte[8 - len]; stream.Write(buf, 0, buf.Length); } } stream.FlushFinalBlock(); return(outstream.ToArray()); }
/// <summary>对称解密算法扩展</summary> /// <param name="sa">算法</param> /// <param name="data">数据</param> /// <param name="pass">密码</param> /// <param name="mode">模式。.Net默认CBC,Java默认ECB</param> /// <param name="padding">填充算法。默认PKCS7,等同Java的PKCS5</param> /// <returns></returns> public static Byte[] Decrypt(this SymmetricAlgorithm sa, Byte[] data, Byte[] pass = null, CipherMode mode = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7) { if (data == null || data.Length < 1) { throw new ArgumentNullException(nameof(data)); } if (pass != null && pass.Length > 0) { var keySize = sa.KeySize / 8; sa.Key = Pad(pass, keySize); var ivSize = sa.IV.Length; sa.IV = Pad(pass, ivSize); sa.Mode = mode; sa.Padding = padding; } using var stream = new CryptoStream(new MemoryStream(data), sa.CreateDecryptor(), CryptoStreamMode.Read); return(stream.ReadBytes()); }
public static byte[] DecryptBlob(byte[] ciphertext, byte[] key, int algCrypt = 26115, PaddingMode padding = PaddingMode.Zeros) { // decrypts a DPAPI blob using 3DES or AES // reference: https://docs.microsoft.com/en-us/windows/desktop/seccrypto/alg-id // 26115 == CALG_3DES // 26128 == CALG_AES_256 if (algCrypt == 26115) { // takes a byte array of ciphertext bytes and a key array, decrypt the blob with 3DES TripleDESCryptoServiceProvider desCryptoProvider = new TripleDESCryptoServiceProvider(); byte[] ivBytes = new byte[8]; desCryptoProvider.Key = key; desCryptoProvider.IV = ivBytes; desCryptoProvider.Mode = CipherMode.CBC; desCryptoProvider.Padding = padding; try { byte[] plaintextBytes = desCryptoProvider.CreateDecryptor() .TransformFinalBlock(ciphertext, 0, ciphertext.Length); return(plaintextBytes); } catch (Exception e) { Console.WriteLine("[x] An exception occured: {0}", e); } return(new byte[0]); } else if (algCrypt == 26128) { // takes a byte array of ciphertext bytes and a key array, decrypt the blob with AES256 AesManaged aesCryptoProvider = new AesManaged(); byte[] ivBytes = new byte[16]; aesCryptoProvider.Key = key; aesCryptoProvider.IV = ivBytes; aesCryptoProvider.Mode = CipherMode.CBC; aesCryptoProvider.Padding = padding; byte[] plaintextBytes = aesCryptoProvider.CreateDecryptor().TransformFinalBlock(ciphertext, 0, ciphertext.Length); return(plaintextBytes); } else { return(new byte[0]); } }
/// <summary> /// 解密 /// </summary> /// <param name="keyArray">密匙</param> /// <param name="toDecryptArray">需要解密的文本</param> /// <param name="iv">偏移量</param> /// <param name="keySize">密匙大小</param> /// <param name="blockSize">块大小</param> /// <param name="cipherMode">加密块密码模式</param> /// <param name="paddingMode">填充类型</param> /// <returns></returns> public static byte[] Decrypt(byte[] keyArray, byte[] toDecryptArray, byte[] iv = null, int keySize = 256, int blockSize = 128, CipherMode cipherMode = CipherMode.ECB, PaddingMode paddingMode = PaddingMode.PKCS7) { using (Aes aes = Aes.Create()) { aes.KeySize = keySize; aes.BlockSize = blockSize; aes.Mode = cipherMode; aes.Padding = paddingMode; aes.Key = keyArray; if (iv != null) { aes.IV = iv; } ICryptoTransform cTransform = aes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length); return(resultArray); } }
internal TwofishManagedTransform(byte[] key, CipherMode mode, byte[] iv, TwofishManagedTransformMode transformMode, PaddingMode paddingMode) { TransformMode = transformMode; PaddingMode = paddingMode; var key32 = new uint[key.Length / 4]; Buffer.BlockCopy(key, 0, key32, 0, key.Length); if (iv != null) { var iv32 = new uint[iv.Length / 4]; Buffer.BlockCopy(iv, 0, iv32, 0, iv.Length); Implementation = new TwofishImplementation(key32, iv32, mode); } else { Implementation = new TwofishImplementation(key32, null, mode); } }
static void Main(string[] args) { Console.WriteLine("書式"); Console.WriteLine("aes EncDecFlg(0=dec,1=enc) dataFile keyFile OutputFile IVFile cypherMode paddingMode keySize blockSize"); if (args.Length < 4) { Console.WriteLine("引数個数 エラー 最低4引数が必要です"); return; } string argEncDecFlg = args[0]; string argDataFile = args[1]; string argkeyFile = args[2]; string argOutFile = args[3]; string argCypherMode = "1"; // CBC がデフォルト //平文の文字列 byte[] data = null; //鍵 byte[] key = null; if (File.Exists(argDataFile)) { data = ReadBinaryFromFile(argDataFile); } else { Console.WriteLine("データファイル エラー ファイルが存在しません"); return; } if (File.Exists(argkeyFile)) { key = ReadBinaryFromFile(argkeyFile); } else { Console.WriteLine("キーファイル エラー ファイルが存在しません"); return; } // 初期化ベクトル byte[] iv = defaultIV; if (args.Length > 4) { string argIV = args[4]; if (File.Exists(argIV)) { iv = ReadBinaryFromFile(argIV); } else { Console.WriteLine("IVファイル エラー ファイルが存在しません"); return; } } if (args.Length > 5) { argCypherMode = args[5]; } string argPaddingMode = "1"; // None がデフォルト if (args.Length > 6) { argPaddingMode = args[6]; } string argKeySizes = "128"; // 128 がデフォルト if (args.Length > 7) { argKeySizes = args[7]; } string argBlockSize = "128"; // 128 がデフォルト if (args.Length > 8) { argBlockSize = args[8]; } bool argCheckResult = ArgCheck(argCypherMode, argPaddingMode, argKeySizes, argBlockSize); if (false == argCheckResult) { // 引数エラー時は終了 return; } Crypt wd = new Crypt(); int encDecFlg = parseStringToInt(argEncDecFlg); // 暗号モード CipherMode cypherMode = (CipherMode)parseStringToInt(argCypherMode); // パディングモード PaddingMode paddingMode = (PaddingMode)parseStringToInt(argPaddingMode); // キーサイズ int keySizes = parseStringToInt(argKeySizes); // ブロックサイズ int blockSize = parseStringToInt(argBlockSize); byte[] dest = null; if (0 == encDecFlg) { dest = wd.Decrypt(data, key, iv, cypherMode, paddingMode, keySizes, blockSize); } else { dest = wd.Encrypt(data, key, iv, cypherMode, paddingMode, keySizes, blockSize); } WriteBinaryToFile(argOutFile, dest); }
/// <summary>コンストラクタ</summary> public Convolution3D(int inchannels, int outchannels, int kwidth, int kheight, int kdepth, int stride, bool use_bias, PaddingMode pad_mode, string label) : base(label) { this.W = new ParameterField( new Tensor(Shape.Kernel3D(inchannels, outchannels, kwidth, kheight, kdepth)), Label + "/w", ParameterCategory.Kernel); this.Bias = use_bias ? new ParameterField( new Tensor(Shape.Vector(outchannels)), Label + "/bias", ParameterCategory.Bias) : null; this.Stride = stride; this.PaddingMode = pad_mode; }
private string Decrypt(string key, string data, CipherMode cMode = CipherMode.ECB, PaddingMode pMode = PaddingMode.None, string iv = "00000000000000000000000000000000") { byte[] derivedData; using (var aes = new AesCryptoServiceProvider { Mode = cMode, Padding = pMode }) using (var ict = aes.CreateDecryptor(BinaryHelper.ConvertOctetStringToBytes(key), BinaryHelper.ConvertOctetStringToBytes(iv))) { byte[] dataBytes = BinaryHelper.ConvertOctetStringToBytes(data); derivedData = ict.TransformFinalBlock(dataBytes, 0, dataBytes.Length); } return(BinaryHelper.ConvertBytesToOctetString(derivedData)); }
internal static int EncryptDataCp(SafeProvHandle hProv, SafeKeyHandle hKey, byte[] data, int ib, int cb, ref byte[] outputBuffer, int outputOffset, PaddingMode paddingMode, bool fDone, bool isStream) { int dwDataLen = (int)cb; // ebp+0x58 int bufLength = cb; // ebp+0x34 if (fDone) { // Мы не используем в отличии от MS реализации Final // поэтому на 8 байт CAPI Padding меньше bufLength += 8; } int remainder = cb & 7; // ebp+0x30 if (cb < 0) { throw new ArgumentOutOfRangeException("cb", SR.ArgumentOutOfRange_NeedNonNegNum); } if (ib < 0) { throw new ArgumentOutOfRangeException("ib", SR.ArgumentOutOfRange_NeedNonNegNum); } if (ib > data.Length) { throw new ArgumentException(SR.Argument_InvalidValue, "ib"); } byte[] tmpBuffer = new byte[bufLength]; // ebp + 0x4c Array.Clear(tmpBuffer, 0, bufLength); Array.Copy(data, ib, tmpBuffer, 0, cb); if (fDone) { byte fill = (byte)(8 - remainder); // ebp - 0x28; switch (paddingMode) { case PaddingMode.None: // [data] if (remainder == 0) { break; } if (isStream) { break; } throw new CryptographicException( SR.Cryptography_InvalidPaddingMode); case PaddingMode.PKCS7: // [data] [length..length] { int c = cb; // ebp+0x44; dwDataLen += fill; while (c < dwDataLen) { tmpBuffer[c++] = fill; } } break; case PaddingMode.Zeros: // [data] [0..0] if (remainder == 0) { break; } dwDataLen += fill; break; case PaddingMode.ANSIX923: // [data] [0..0] [length] { int c = cb; // ebp+0x48; dwDataLen += fill; // без while: итак 0. tmpBuffer[dwDataLen - 1] = fill; break; } case PaddingMode.ISO10126: // [data] [random] [length] { byte[] tmpBuf = new byte[fill - 1]; if (hProv == null || hProv.IsInvalid) { CspParameters gostParameters = new CspParameters(GostConstants.PROV_GOST_2001_DH); using (var rng = new GostRngCryptoServiceProvider(gostParameters)) { rng.GetBytes(tmpBuf); } } else { using (var rng = new GostRngCryptoServiceProvider(hProv)) { rng.GetBytes(tmpBuf); } } tmpBuf.CopyTo(tmpBuffer, cb); dwDataLen += fill; tmpBuffer[dwDataLen - 1] = fill; break; } default: throw new ArgumentException( SR.Cryptography_InvalidPaddingMode ); } } // Утверждалось, что "Это похоже ошибка CSP. Не дает шифровать 0 байт в конце." // if (dwDataLen != 0) // // Не используем CAPI Padding! bool ret = Interop.Advapi32.CryptEncrypt(hKey, SafeHashHandle.InvalidHandle, false, 0, tmpBuffer, ref dwDataLen, (int)bufLength); if (!ret) { throw new CryptographicException(Interop.CPError.GetLastWin32Error()); } if (outputBuffer == null) { outputBuffer = new byte[dwDataLen]; Array.Copy(tmpBuffer, 0, outputBuffer, 0, dwDataLen); } else { if (outputOffset < 0) { throw new ArgumentOutOfRangeException("outputOffset", SR.ArgumentOutOfRange_NeedNonNegNum); } if (outputBuffer.Length < dwDataLen) { throw new ArgumentException(SR.Argument_InvalidValue); } if (outputBuffer.Length - dwDataLen < outputOffset) { throw new ArgumentException(SR.Argument_InvalidValue); } Array.Copy(tmpBuffer, 0, outputBuffer, outputOffset, dwDataLen); } return((int)dwDataLen); }
internal static int DecryptDataCp(SafeKeyHandle hKey, byte[] data, int ib, int cb, ref byte[] outputBuffer, int outputOffset, PaddingMode PaddingMode, bool fDone) { int dwDataLen = (int)cb; // ebp+0x5C if (ib < 0) { throw new ArgumentOutOfRangeException("ib", SR.ArgumentOutOfRange_NeedNonNegNum); } if (cb < 0) { throw new ArgumentOutOfRangeException("cb", SR.ArgumentOutOfRange_NeedNonNegNum); } if ((ib > data.Length) || (ib + cb > data.Length)) { throw new ArgumentException(SR.Argument_InvalidValue); } // CryptDecrypt использует один буфер с данными, // поэтому от new не избавиться. byte[] tmpBuffer = new byte[dwDataLen]; // ebp + 0x50 Array.Copy(data, ib, tmpBuffer, 0, dwDataLen); if (!Interop.Advapi32.CryptDecrypt( hKey, SafeHashHandle.InvalidHandle, false, 0, tmpBuffer, ref dwDataLen)) { throw new CryptographicException(Interop.CPError.GetLastWin32Error()); } int realLength = (int)dwDataLen; // ebp + 0x34 if (fDone) { byte fill = 0; if (PaddingMode == PaddingMode.PKCS7 // [data] [length..length] || PaddingMode == PaddingMode.ANSIX923 // [data] [0..0] [length] || PaddingMode == PaddingMode.ISO10126 // [data] [random] [length] ) { if (dwDataLen < 8) { throw new CryptographicException(GostConstants.NTE_BAD_DATA); } fill = tmpBuffer[dwDataLen - 1]; // ebp + 0x4C if (fill > 8) { throw new CryptographicException(GostConstants.NTE_BAD_DATA); } if (PaddingMode == PaddingMode.PKCS7) { for (int i = dwDataLen - fill; i < dwDataLen - 1; i++) { if (tmpBuffer[i] != fill) { throw new CryptographicException(GostConstants.NTE_BAD_DATA); } } } else if (PaddingMode == PaddingMode.ANSIX923) { for (int i = dwDataLen - fill; i < dwDataLen - 1; i++) { if (tmpBuffer[i] != 0) { throw new CryptographicException(GostConstants.NTE_BAD_DATA); } } } } else if (PaddingMode != PaddingMode.None && // [data] PaddingMode != PaddingMode.Zeros) // [data] [0..0] { throw new ArgumentException(SR.Cryptography_InvalidPaddingMode); } realLength -= fill; } if (outputBuffer == null) { outputBuffer = new byte[realLength]; Array.Copy(tmpBuffer, 0, outputBuffer, 0, realLength); } else { if (outputOffset < 0) { throw new ArgumentOutOfRangeException("outputOffset", SR.ArgumentOutOfRange_NeedNonNegNum); } if ((outputBuffer.Length < realLength) || (outputBuffer.Length - realLength < outputOffset)) { throw new ArgumentException(SR.Argument_InvalidValue); } Array.Copy(tmpBuffer, 0, outputBuffer, outputOffset, realLength); } return(realLength); }
XmlElement VerifyInput2(MessageBuffer buf) { Message msg2 = buf.CreateMessage(); StringWriter sw = new StringWriter(); using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter(XmlWriter.Create(sw))) { msg2.WriteMessage(w); } XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(sw.ToString()); // decrypt the key with service certificate privkey PaddingMode mode = PaddingMode.PKCS7; // not sure which is correct ... ANSIX923, ISO10126, PKCS7, Zeros, None. EncryptedXml encXml = new EncryptedXml(doc); encXml.Padding = mode; X509Certificate2 cert2 = new X509Certificate2("Test/Resources/test.pfx", "mono"); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("s", "http://www.w3.org/2003/05/soap-envelope"); nsmgr.AddNamespace("c", "http://schemas.xmlsoap.org/ws/2005/02/sc"); nsmgr.AddNamespace("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); nsmgr.AddNamespace("e", "http://www.w3.org/2001/04/xmlenc#"); nsmgr.AddNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#"); XmlNode n = doc.SelectSingleNode("//o:Security/e:EncryptedKey/e:CipherData/e:CipherValue", nsmgr); Assert.IsNotNull(n, "premise: enckey does not exist"); string raw = n.InnerText; byte [] rawbytes = Convert.FromBase64String(raw); RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert2.PrivateKey; byte [] decryptedKey = EncryptedXml.DecryptKey(rawbytes, rsa, true); //rsa.Decrypt (rawbytes, true); #if false // create derived keys Dictionary <string, byte[]> keys = new Dictionary <string, byte[]> (); InMemorySymmetricSecurityKey skey = new InMemorySymmetricSecurityKey(decryptedKey); foreach (XmlElement el in doc.SelectNodes("//o:Security/c:DerivedKeyToken", nsmgr)) { n = el.SelectSingleNode("c:Offset", nsmgr); int offset = (n == null) ? 0 : int.Parse(n.InnerText, CultureInfo.InvariantCulture); n = el.SelectSingleNode("c:Length", nsmgr); int length = (n == null) ? 32 : int.Parse(n.InnerText, CultureInfo.InvariantCulture); n = el.SelectSingleNode("c:Label", nsmgr); byte [] label = (n == null) ? decryptedKey : Convert.FromBase64String(n.InnerText); n = el.SelectSingleNode("c:Nonce", nsmgr); byte [] nonce = (n == null) ? new byte [0] : Convert.FromBase64String(n.InnerText); byte [] derkey = skey.GenerateDerivedKey( //SecurityAlgorithms.Psha1KeyDerivation, "http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1", // FIXME: maybe due to the label, this key resolution somehow does not seem to work. label, nonce, length * 8, offset); keys [el.GetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")] = derkey; } #endif // decrypt the signature with the decrypted key #if true n = doc.SelectSingleNode("//o:Security/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr); Assert.IsNotNull(n, "premise: encdata does not exist"); raw = n.InnerText; rawbytes = Convert.FromBase64String(raw); Rijndael aes = RijndaelManaged.Create(); // aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)]; aes.Key = decryptedKey; aes.Mode = CipherMode.CBC; aes.Padding = mode; MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(rawbytes, 0, rawbytes.Length); cs.Close(); byte [] decryptedSignature = ms.ToArray(); #else Rijndael aes = RijndaelManaged.Create(); // aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)]; aes.Key = decryptedKey; aes.Mode = CipherMode.CBC; aes.Padding = mode; EncryptedData ed = new EncryptedData(); n = doc.SelectSingleNode("//o:Security/e:EncryptedData", nsmgr); Assert.IsNotNull(n, "premise: encdata does not exist"); ed.LoadXml(n as XmlElement); byte [] decryptedSignature = encXml.DecryptData(ed, aes); #endif //Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedSignature)); //Console.Error.WriteLine ("============= Decrypted Signature End ==========="); // decrypt the body with the decrypted key #if true n = doc.SelectSingleNode("//s:Body/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr); Assert.IsNotNull(n, "premise: encdata does not exist"); raw = n.InnerText; rawbytes = Convert.FromBase64String(raw); // aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)]; aes.Key = decryptedKey; ms = new MemoryStream(); cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(rawbytes, 0, rawbytes.Length); cs.Close(); byte [] decryptedBody = ms.ToArray(); #else // decrypt the body with the decrypted key EncryptedData ed2 = new EncryptedData(); XmlElement el = doc.SelectSingleNode("/s:Envelope/s:Body/e:EncryptedData", nsmgr) as XmlElement; ed2.LoadXml(el); // aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)]; aes.Key = decryptedKey; byte [] decryptedBody = encXml.DecryptData(ed2, aes); #endif //foreach (byte b in decryptedBody) Console.Error.Write ("{0:X02} ", b); Console.Error.WriteLine(Encoding.UTF8.GetString(decryptedBody)); Console.Error.WriteLine("============= Decrypted Body End ==========="); // FIXME: find out what first 16 bytes mean. for (int mmm = 0; mmm < 16; mmm++) { decryptedBody [mmm] = 0x20; } doc.LoadXml(Encoding.UTF8.GetString(decryptedBody)); Assert.AreEqual("RequestSecurityToken", doc.DocumentElement.LocalName, "#b-1"); Assert.AreEqual("http://schemas.xmlsoap.org/ws/2005/02/trust", doc.DocumentElement.NamespaceURI, "#b-2"); return(doc.DocumentElement); }
private static void TestDESTransformDirectKey( CipherMode cipherMode, PaddingMode paddingMode, byte[] key, byte[] iv, byte[] plainBytes, byte[] cipherBytes, int?feedbackSize = default) { byte[] liveEncryptBytes; byte[] liveDecryptBytes; byte[] liveOneShotDecryptBytes = null; byte[] liveOneShotEncryptBytes = null; using (DES des = DESFactory.Create()) { des.Mode = cipherMode; des.Padding = paddingMode; des.Key = key; if (feedbackSize.HasValue) { des.FeedbackSize = feedbackSize.Value; } liveEncryptBytes = DESEncryptDirectKey(des, key, iv, plainBytes); liveDecryptBytes = DESDecryptDirectKey(des, key, iv, cipherBytes); if (DESFactory.OneShotSupported) { if (cipherMode == CipherMode.ECB) { liveOneShotDecryptBytes = des.DecryptEcb(cipherBytes, paddingMode); liveOneShotEncryptBytes = des.EncryptEcb(plainBytes, paddingMode); } else if (cipherMode == CipherMode.CBC) { liveOneShotDecryptBytes = des.DecryptCbc(cipherBytes, iv, paddingMode); liveOneShotEncryptBytes = des.EncryptCbc(plainBytes, iv, paddingMode); } else if (cipherMode == CipherMode.CFB) { liveOneShotDecryptBytes = des.DecryptCfb(cipherBytes, iv, paddingMode, feedbackSizeInBits: feedbackSize.Value); liveOneShotEncryptBytes = des.EncryptCfb(plainBytes, iv, paddingMode, feedbackSizeInBits: feedbackSize.Value); } } } Assert.Equal(cipherBytes, liveEncryptBytes); Assert.Equal(plainBytes, liveDecryptBytes); if (liveOneShotDecryptBytes is not null) { Assert.Equal(plainBytes, liveOneShotDecryptBytes); } if (liveOneShotEncryptBytes is not null) { Assert.Equal(cipherBytes, liveOneShotEncryptBytes); } }
private static byte[] RemovePadding(byte[] outputBuffer, PaddingMode paddingMode) { if (paddingMode == PaddingMode.PKCS7) { var padding = outputBuffer[outputBuffer.Length - 1]; if ((padding < 1) || (padding > 16)) { throw new CryptographicException("Invalid padding."); } for (var i = outputBuffer.Length - padding; i < outputBuffer.Length; i++) { if (outputBuffer[i] != padding) { throw new CryptographicException("Invalid padding."); } } var newOutputBuffer = new byte[outputBuffer.Length - padding]; Buffer.BlockCopy(outputBuffer, 0, newOutputBuffer, 0, newOutputBuffer.Length); return(newOutputBuffer); } else if (paddingMode == PaddingMode.Zeros) { var newOutputLength = outputBuffer.Length; for (var i = outputBuffer.Length - 1; i >= outputBuffer.Length - 16; i--) { if (outputBuffer[i] != 0) { newOutputLength = i + 1; break; } } if (newOutputLength == outputBuffer.Length) { return(outputBuffer); } else { var newOutputBuffer = new byte[newOutputLength]; Buffer.BlockCopy(outputBuffer, 0, newOutputBuffer, 0, newOutputBuffer.Length); return(newOutputBuffer); } } else if (paddingMode == PaddingMode.ANSIX923) { var padding = outputBuffer[outputBuffer.Length - 1]; if ((padding < 1) || (padding > 16)) { throw new CryptographicException("Invalid padding."); } for (var i = outputBuffer.Length - padding; i < outputBuffer.Length - 1; i++) { if (outputBuffer[i] != 0) { throw new CryptographicException("Invalid padding."); } } var newOutputBuffer = new byte[outputBuffer.Length - padding]; Buffer.BlockCopy(outputBuffer, 0, newOutputBuffer, 0, newOutputBuffer.Length); return(newOutputBuffer); } else if (paddingMode == PaddingMode.ISO10126) { var padding = outputBuffer[outputBuffer.Length - 1]; if ((padding < 1) || (padding > 16)) { throw new CryptographicException("Invalid padding."); } var newOutputBuffer = new byte[outputBuffer.Length - padding]; Buffer.BlockCopy(outputBuffer, 0, newOutputBuffer, 0, newOutputBuffer.Length); return(newOutputBuffer); } else { return(outputBuffer); } }
public void EncryptAndDecrypt(CipherMode mode, PaddingMode padding, string iv, string cipherText) => Verify(mode, padding, PlainText, cipherText, Key, iv);
/// <summary> /// AES解密 /// </summary> /// <param name="value"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <returns></returns> public static string AesDecryptJava(string value, string key, CipherMode cipherMode, PaddingMode paddingMode, string iv = null) { if (string.IsNullOrEmpty(value)) { return(string.Empty); } if (key == null) { throw new Exception("密钥不能为空。"); } var kgen = Org.BouncyCastle.Security.GeneratorUtilities.GetKeyGenerator("AES"); var secureRandom = Org.BouncyCastle.Security.SecureRandom.GetInstance("SHA1PRNG"); secureRandom.SetSeed(Encoding.ASCII.GetBytes(key)); kgen.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(secureRandom, 128)); var _keyByte = kgen.GenerateKey(); var _valueByte = Convert.FromBase64String(value); using (var aes = new RijndaelManaged()) { aes.IV = !string.IsNullOrEmpty(iv) ? Encoding.UTF8.GetBytes(iv) : Encoding.UTF8.GetBytes(key.Substring(0, 16)); aes.Key = _keyByte; aes.Mode = cipherMode; aes.Padding = paddingMode; var cryptoTransform = aes.CreateDecryptor(); var resultArray = cryptoTransform.TransformFinalBlock(_valueByte, 0, _valueByte.Length); return(Encoding.UTF8.GetString(resultArray)); } }
protected UniversalCryptoTransform(PaddingMode paddingMode, BasicSymmetricCipher basicSymmetricCipher) { PaddingMode = paddingMode; BasicSymmetricCipher = basicSymmetricCipher; }
/// <summary> /// AES加密 /// </summary> /// <param name="value"></param> /// <param name="key"></param> /// <param name="cipherMode"></param> /// <param name="paddingMode"></param> /// <param name="iv"></param> /// <returns></returns> public static string AesEncrypt(string value, string key, CipherMode cipherMode, PaddingMode paddingMode, string iv = null) { if (string.IsNullOrEmpty(value)) { return(string.Empty); } if (key == null) { throw new Exception("密钥不能为空。"); } if (key.Length < 16) { throw new Exception("指定的密钥长度不能少于16位。"); } if (key.Length > 32) { throw new Exception("指定的密钥长度不能多于32位。"); } if (key.Length != 16 && key.Length != 24 && key.Length != 32) { throw new Exception("指定的密钥长度不明确。"); } var _keyByte = Encoding.UTF8.GetBytes(key); var _valueByte = Encoding.UTF8.GetBytes(value); using (var aes = new RijndaelManaged()) { aes.IV = !string.IsNullOrEmpty(iv) ? Encoding.UTF8.GetBytes(iv) : Encoding.UTF8.GetBytes(key.Substring(0, 16)); aes.Key = _keyByte; aes.Mode = cipherMode; aes.Padding = paddingMode; var cryptoTransform = aes.CreateEncryptor(); var resultArray = cryptoTransform.TransformFinalBlock(_valueByte, 0, _valueByte.Length); return(Convert.ToBase64String(resultArray, 0, resultArray.Length)); } }
protected AesNativeCryptoTransform(CipherMode cipherMode, PaddingMode paddingMode, int blockSize) { _blockSize = blockSize; CipherMode = cipherMode; PaddingMode = paddingMode; }