C#对称加密(AES加密)每次生成的结果都不同的实现思路和代码实例
程序员文章站
2023-12-05 22:50:28
思路:使用随机向量,把随机向量放入密文中,每次解密时从密文中截取前16位,其实就是我们之前加密的随机向量。
代码:
public static st...
思路:使用随机向量,把随机向量放入密文中,每次解密时从密文中截取前16位,其实就是我们之前加密的随机向量。
代码:
public static string encrypt(string plaintext, string aeskey) { rijndaelmanaged rijndaelcipher = new rijndaelmanaged(); byte[] inputbytearray = encoding.utf8.getbytes(plaintext);//得到需要加密的字节数组 rijndaelcipher.key = convert.frombase64string(aeskey);//加解密双方约定好密钥:aeskey rijndaelcipher.generateiv(); byte[] keyiv = rijndaelcipher.iv; byte[] cipherbytes = null; using (memorystream ms = new memorystream()) { using (cryptostream cs = new cryptostream(ms, rijndaelcipher.createencryptor(), cryptostreammode.write)) { cs.write(inputbytearray, 0, inputbytearray.length); cs.flushfinalblock(); cipherbytes = ms.toarray();//得到加密后的字节数组 cs.close(); ms.close(); } } var allencrypt = new byte[keyiv.length + cipherbytes.length]; buffer.blockcopy(keyiv, 0, allencrypt, 0, keyiv.length); buffer.blockcopy(cipherbytes, 0, allencrypt, keyiv.length * sizeof(byte), cipherbytes.length); return convert.tobase64string(allencrypt); } public static string decrypt(string showtext, string aeskey) { string result = string.empty; try { byte[] ciphertext = convert.frombase64string(showtext); int length = ciphertext.length; symmetricalgorithm rijndaelcipher = rijndael.create(); rijndaelcipher.key = convert.frombase64string(aeskey);//加解密双方约定好的密钥 byte[] iv = new byte[16]; buffer.blockcopy(ciphertext, 0, iv, 0, 16); rijndaelcipher.iv = iv; byte[] decryptbytes = new byte[length - 16]; byte[] passwdtext = new byte[length - 16]; buffer.blockcopy(ciphertext, 16, passwdtext, 0, length - 16); using (memorystream ms = new memorystream(passwdtext)) { using (cryptostream cs = new cryptostream(ms, rijndaelcipher.createdecryptor(), cryptostreammode.read)) { cs.read(decryptbytes, 0, decryptbytes.length); cs.close(); ms.close(); } } result = encoding.utf8.getstring(decryptbytes).replace("\0", ""); ///将字符串后尾的'\0'去掉 } catch { } return result; }
调用:
string jiami = myaestools.encrypt(textbox1.text, "abcdefgh12345678abcdefgh12345678"); string jiemi = myaestools.decrypt(textbox3.text, "abcdefgh12345678abcdefgh12345678");