質問: c#で文字列を暗号化および復号化する? c#で文字列を暗号化および復号化する方法
回答: これは、基本的な動く部分を示すために、ランダムivおよびhmacとパスワードから派生した鍵でaes cbcモードを使用してc#で文字列を暗号化する簡単な例です。private byte[] encryptbytes(byte[] key, byte[] plaintext) { using (var cipher = new rijndaelmanaged { key = key }) { using (var encryptor = cipher.createencryptor()) { var ciphertext = encryptor.transformfinalblock(plaintext, 0, plaintext.length); // iv is prepended to ciphertext return cipher.iv.concat(ciphertext).toarray(); } } } private byte[] decryptbytes(byte[] key, byte[] packed) { using (var cipher = new rijndaelmanaged { key = key }) { int ivsize = cipher.blocksize / 8; cipher.iv = packed.take(ivsize).toarray(); using (var encryptor = cipher.createdecryptor()) { return encryptor.transformfinalblock(packed, ivsize, packed.length - ivsize); } } } private byte[] addmac(byte[] key, byte[] data) { using (var hmac = new hmacsha256(key)) { var macbytes = hmac.computehash(data); // hmac is appended to data return data.concat(macbytes).toarray(); } } private bool badmac(byte[] found, byte[] computed) { int mismatch = 0; // aim for consistent timing regardless of inputs for (int i = 0; i < found.length; i++) { mismatch += found[i] == computed[i] ? 0 : 1; } return mismatch != 0; } private byte[] removemac(byte[] key, byte[] data) { using (var hmac = new hmacsha256(key)) { int macsize = hmac.hashsize / 8; var packed = data.take(data.length - macsize).toarray(); var foundmac = data.skip(packed.length).toarray(); var computedmac = hmac.computehash(packed); if (this.badmac(foundmac, computedmac)) { throw new exception("bad mac"); } return packed; } } private list<byte[]> derivetwokeys(string password) { var salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; var kdf = new rfc2898derivebytes(password, salt, 10000); var bytes = kdf.getbytes(32); // two keys 128 bits each return new list<byte[]> { bytes.take(16).toarray(), bytes.skip(16).toarray() }; } public byte[] encryptstring(string password, string message) { var keys = this.derivetwokeys(password); var plaintext = encoding.utf8.getbytes(message); var packed = this.encryptbytes(keys[0], plaintext); return this.addmac(keys[1], packed); } public string decryptstring(string password, byte[] secret) { var keys = this.derivetwokeys(password); var packed = this.removemac(keys[1], secret); var plaintext = this.decryptbytes(keys[0], packed); return encoding.utf8.getstring(plaintext); } public void example() { var password = "correcthorsebatterystaple"; var secret = this.encryptstring(password, "hello world"); console.writeline("secret: " + bitconverter.tostring(secret)); var recovered = this.decryptstring(password, secret); console.writeline(recovered); }