【发布时间】:2015-10-11 01:25:26
【问题描述】:
我有一个用 VB 编写的加密类,我正在尝试将其转换为 C#。在VB代码中,有一段代码:
' Allocate byte array to hold our salt.
Dim salt() As Byte = New Byte(saltLen - 1) {}
' Populate salt with cryptographically strong bytes.
Dim rng As RNGCryptoServiceProvider = New RNGCryptoServiceProvider()
rng.GetNonZeroBytes(salt)
' Split salt length (always one byte) into four two-bit pieces and
' store these pieces in the first four bytes of the salt array.
salt(0) = ((salt(0) And &HFC) Or (saltLen And &H3))
salt(1) = ((salt(1) And &HF3) Or (saltLen And &HC))
salt(2) = ((salt(2) And &HCF) Or (saltLen And &H30))
salt(3) = ((salt(3) And &H3F) Or (saltLen And &HC0))
我将它翻译成 C# 并最终得到以下内容:
// Allocate byte array to hold our salt.
byte[] salt = new byte[saltLen];
// Populate salt with cryptographically strong bytes.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetNonZeroBytes(salt);
// Split salt length (always one byte) into four two-bit pieces and
// store these pieces in the first four bytes of the salt array.
salt[0] = ((salt[0] & 0xfc) | (saltLen & 0x3));
salt[1] = ((salt[1] & 0xf3) | (saltLen & 0xc));
salt[2] = ((salt[2] & 0xcf) | (saltLen & 0x30));
salt[3] = ((salt[3] & 0x3f) | (saltLen & 0xc0));
当我尝试编译它时,我在分配给 salt[] 的 4 个分配中的每一个都收到错误 - 代码块中的最后 4 行。错误是:
错误 255 无法将类型“int”隐式转换为“byte”。明确的 存在转换(您是否缺少演员表?)
请原谅我的无知 - 我是一个相对的 C# 新手,我尝试了以下但仍然有错误:
salt[0] = ((salt[0] & 0xfc as byte) | (saltLen & 0x3 as byte));
salt[0] = ((salt[0] & (byte)0xfc) | (saltLen & (byte)0x3));
我不太确定这段代码在做什么,这也许可以解释为什么我无法弄清楚如何修复它。
感谢任何帮助。
【问题讨论】:
-
试试:
salt[0] = (byte)((salt[0] & 0xfc) | (saltLen & 0x3));
标签: c# vb.net code-translation