public static byte[] _CustomEncryptCbcPkcs7(ReadOnlySpan <byte> data, ReadOnlySpan <byte> iv, byte[] key) { var len = data.Length / 16 + 1; var output = new byte[len * 16]; var prevBlock = iv; int i = 0; for (; i < len - 1; i++) { var xored = Xor.ApplyFixed(prevBlock, data.Slice(i * 16, 16)); var encrypted = EncryptEcb(xored, key, PaddingMode.None); Array.Copy(encrypted, 0, output, i * 16, 16); prevBlock = encrypted; } var padded = PKCS7.Pad(data.Slice(i * 16, data.Length % 16), 16); Array.Copy(EncryptEcb(Xor.ApplyFixed(prevBlock, padded), key), 0, output, i * 16, 16); return(output); }
public static ReadOnlySpan <byte> _CustomDecryptCbcPkcs7(ReadOnlySpan <byte> cipher, ReadOnlySpan <byte> iv, byte[] key) { var blocks = cipher.Length / 16; var output = new byte[cipher.Length]; for (int i = blocks - 1; i >= 0; --i) { ReadOnlySpan <byte> prevBlock; if (i == 0) { prevBlock = iv; } else { prevBlock = cipher.Slice((i - 1) * 16, 16); } var decryptedBlock = DecryptEcb(cipher.Slice(i * 16, 16), key, PaddingMode.None); var xored = Xor.ApplyFixed(prevBlock, decryptedBlock); Array.Copy(xored, 0, output, i * 16, 16); } return(PKCS7.StripPad(output)); }