[英]c# encryption and decryption
C# 2005 I am using a simple encrypt and descrypt for a IP address. C#2005我正在对IP地址使用简单的加密和解密。 The app on the remote server will encrypt the ip address and the client will decrypt it. 远程服务器上的应用程序将加密IP地址,客户端将对其解密。 However, when the client descrypts the IP I only get some of the IP address back. 但是,当客户端解密IP时,我只会得到一些IP地址。 The rest is rubbish. 剩下的就是垃圾。 Before: 123.456.78.98 After: fheh&^G.78.98 之前:123.456.78.98之后:fheh&^ G.78.98
Many thanks, 非常感谢,
/// Encrypt the SIP IP address in the remote server
private void encryptSIP_IP(string sip_ip)
{
TripleDESCryptoServiceProvider encrypt = new TripleDESCryptoServiceProvider();
/// Private key
byte[] key = { 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 144, 89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 0};
encrypt.Key = key;
byte[] byteSIP = System.Text.Encoding.Default.GetBytes(sip_ip);
ICryptoTransform encryptor = encrypt.CreateEncryptor();
byte[] encrypted_sip = encryptor.TransformFinalBlock(byteSIP, 0, byteSIP.Length);
/// This will decrypt in the client application
private void decryptSIP_IP(byte[] encrypted_sip)
{
TripleDESCryptoServiceProvider decrypt = new TripleDESCryptoServiceProvider();
/// Private key
byte[] key = { 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 144, 89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 0 };
decrypt.Key = key;
ICryptoTransform decryptor = decrypt.CreateDecryptor();
byte[] original = decryptor.TransformFinalBlock(encrypted_sip, 0, encrypted_sip.Length);
string ip = System.Text.Encoding.Default.GetString(original);
}
}
Along with a key you need an Initialization Vector (8 bytes for your case): 除了键,还需要一个初始化向量 (对于您的情况为8个字节):
// To Encrypt
encrypt.IV = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
// Use same IV to decrypt
decrypt.IV = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
As darin already said, you need to set the Initialization Vector. 正如darin所说,您需要设置初始化向量。 If possible, choose a random one for each encryption process and transfer/save it in clear text. 如果可能,请为每个加密过程选择一个随机数,然后以明文形式传输/保存。
By the way, you should look into CryptoStream instead of working with TransformBlock/TransformFinalBlock ... it's much cleaner, imho. 顺便说一句,您应该研究CryptoStream而不是使用TransformBlock / TransformFinalBlock ...,它更干净了,恕我直言。
Have you tried setting the encoding explicitly on both sides? 您是否尝试过在两侧明确设置编码? Maybe the default is different. 可能默认值是不同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.