- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我对以下问题的结果有些随意:
并创建了以下类文件...
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace T1.CoreUtils.Utilities
{
public static class CryptoUtility
{
public static string Encrypt(string input, string passphrase = null)
{
byte[] key, iv;
DeriveKeyAndIV(Encoding.ASCII.GetBytes(passphrase), null, 1, out key, out iv);
return Convert.ToBase64String(EncryptStringToBytes(input, key, iv));
}
public static string Decrypt(string inputBase64, string passphrase = null)
{
byte[] key, iv;
DeriveKeyAndIV(Encoding.ASCII.GetBytes(passphrase), null, 1, out key, out iv);
return DecryptStringFromBytes(Convert.FromBase64String(inputBase64), key, iv);
}
private static void DeriveKeyAndIV(byte[] data, byte[] salt, int count, out byte[] key, out byte[] iv)
{
List<byte> hashList = new List<byte>();
byte[] currentHash = new byte[0];
int preHashLength = data.Length + ((salt != null) ? salt.Length : 0);
byte[] preHash = new byte[preHashLength];
System.Buffer.BlockCopy(data, 0, preHash, 0, data.Length);
if (salt != null)
System.Buffer.BlockCopy(salt, 0, preHash, data.Length, salt.Length);
MD5 hash = MD5.Create();
currentHash = hash.ComputeHash(preHash);
for (int i = 1; i < count; i++)
{
currentHash = hash.ComputeHash(currentHash);
}
hashList.AddRange(currentHash);
while (hashList.Count < 48) // for 32-byte key and 16-byte iv
{
preHashLength = currentHash.Length + data.Length + ((salt != null) ? salt.Length : 0);
preHash = new byte[preHashLength];
System.Buffer.BlockCopy(currentHash, 0, preHash, 0, currentHash.Length);
System.Buffer.BlockCopy(data, 0, preHash, currentHash.Length, data.Length);
if (salt != null)
System.Buffer.BlockCopy(salt, 0, preHash, currentHash.Length + data.Length, salt.Length);
currentHash = hash.ComputeHash(preHash);
for (int i = 1; i < count; i++)
{
currentHash = hash.ComputeHash(currentHash);
}
hashList.AddRange(currentHash);
}
hash.Clear();
key = new byte[32];
iv = new byte[16];
hashList.CopyTo(0, key, 0, 32);
hashList.CopyTo(32, iv, 0, 16);
}
static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
}
从这里,我通过 Node 生成了以下内容:
var crypto = require('crypto');
var input = "This is î╥≤ what it is.";
var passkey= "This is my password.";
var cipher = crypto.createCipher('aes-256-cbc', passkey);
var encrypted = cipher.update(input, 'utf8', 'base64') + cipher.final('base64');
encrypted
// '9rTbNbfJkYVE2m5d8g/8b/qAfeCU9rbk09Na/Pw0bak='
input = "I am the walrus, coo coo cachoo!";
passkey = "I am a ≥ò'ÿ boy baby!";
cipher = crypto.createCipher('aes-256-cbc', passkey);
encrypted = cipher.update(input, 'utf8', 'base64') + cipher.final('base64');
// 'j/e+f5JU5yerSvO7FBJzR1tGro0Ie3L8sWYaupRW1JJhraGqBfQ9z+h85VhSzEjD'
var decipher = crypto.createDecipher('aes-256-cbc', passkey);
var plain = decipher.update(encrypted, 'base64', 'utf8') + decipher.final('utf8');
plain
// 'I am the walrus, coo coo cachoo!'
据此,我创建了以下测试用例:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace T1.CoreUtils.Test.Utilities.Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void EncryptReturnsExpectedValue1_unicode_in_plaintext()
{
var passkey = "This is my password.";
var plain = "This is î╥≤ what it is.";
var encrypted = "9rTbNbfJkYVE2m5d8g/8b/qAfeCU9rbk09Na/Pw0bak=";
var actual = T1.CoreUtils.Utilities.CryptoUtility.Encrypt(plain, passkey);
Assert.AreEqual(encrypted, actual);
}
[TestMethod]
public void EncryptReturnsExpectedValue2_unicode_in_passkey()
{
var passkey = "I am a ≥ò'ÿ boy baby!";
var plain = "I am the walrus, coo coo cachoo!";
var encrypted = "j/e+f5JU5yerSvO7FBJzR1tGro0Ie3L8sWYaupRW1JJhraGqBfQ9z+h85VhSzEjD";
var actual = T1.CoreUtils.Utilities.CryptoUtility.Encrypt(plain, passkey);
Assert.AreEqual(encrypted, actual);
}
[TestMethod]
public void DecryptReturnsExpectedValue1()
{
var passkey = "This is my password.";
var plain = "This is î╥≤ what it is.";
var encrypted = "9rTbNbfJkYVE2m5d8g/8b/qAfeCU9rbk09Na/Pw0bak=";
var actual = T1.CoreUtils.Utilities.CryptoUtility.Decrypt(encrypted, passkey);
Assert.AreEqual(plain, actual);
}
[TestMethod]
public void DecryptReturnsExpectedValue2()
{
var passkey = "I am a ≥ò'ÿ boy baby!";
var plain = "I am the walrus, coo coo cachoo!";
var encrypted = "j/e+f5JU5yerSvO7FBJzR1tGro0Ie3L8sWYaupRW1JJhraGqBfQ9z+h85VhSzEjD";
var actual = T1.CoreUtils.Utilities.CryptoUtility.Decrypt(encrypted, passkey);
Assert.AreEqual(plain, actual);
}
}
}
通行证:
失败:
我只能猜测问题出在 DeriveKeyAndIV
方法中。如果我自己找到它,我会尝试几种不同的方法并回答。
最佳答案
好的,在检查 node.js 的加密源代码后,我确定编码使用了一个新的 Buffer(passkey, 'binary'),它只使用原始值 x 和 0xFF 作为所使用的字节,所以我在 C# 中创建了一个匹配方法...这是有问题的方法...
private static byte[] RawBytesFromString(string input)
{
var ret = new List<Byte>();
foreach (char x in input)
{
var c = (byte)((ulong)x & 0xFF);
ret.Add(c);
}
return ret.ToArray();
}
以及更新/工作的 CryptoUtil.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace T1.CoreUtils.Utilities
{
public static class CryptoUtility
{
/* Wanting to stay compatible with NodeJS
* http://stackoverflow.com/questions/18502375/aes256-encryption-decryption-in-both-nodejs-and-c-sharp-net/
* http://stackoverflow.com/questions/12261540/decrypting-aes256-encrypted-data-in-net-from-node-js-how-to-obtain-iv-and-key
* http://stackoverflow.com/questions/8008253/c-sharp-version-of-openssl-evp-bytestokey-method
*
* var cipher = crypto.createCipher('aes-256-cbc', 'passphrase');
* var encrypted = cipher.update("test", 'utf8', 'base64') + cipher.final('base64');
*
* var decipher = crypto.createDecipher('aes-256-cbc', 'passphrase');
* var plain = decipher.update(encrypted, 'base64', 'utf8') + decipher.final('utf8');
*/
public static string Encrypt(string input, string passphrase = null)
{
byte[] key, iv;
DeriveKeyAndIV(RawBytesFromString(passphrase), null, 1, out key, out iv);
return Convert.ToBase64String(EncryptStringToBytes(input, key, iv));
}
public static string Decrypt(string inputBase64, string passphrase = null)
{
byte[] key, iv;
DeriveKeyAndIV(RawBytesFromString(passphrase), null, 1, out key, out iv);
return DecryptStringFromBytes(Convert.FromBase64String(inputBase64), key, iv);
}
private static byte[] RawBytesFromString(string input)
{
var ret = new List<Byte>();
foreach (char x in input)
{
var c = (byte)((ulong)x & 0xFF);
ret.Add(c);
}
return ret.ToArray();
}
private static void DeriveKeyAndIV(byte[] data, byte[] salt, int count, out byte[] key, out byte[] iv)
{
List<byte> hashList = new List<byte>();
byte[] currentHash = new byte[0];
int preHashLength = data.Length + ((salt != null) ? salt.Length : 0);
byte[] preHash = new byte[preHashLength];
System.Buffer.BlockCopy(data, 0, preHash, 0, data.Length);
if (salt != null)
System.Buffer.BlockCopy(salt, 0, preHash, data.Length, salt.Length);
MD5 hash = MD5.Create();
currentHash = hash.ComputeHash(preHash);
for (int i = 1; i < count; i++)
{
currentHash = hash.ComputeHash(currentHash);
}
hashList.AddRange(currentHash);
while (hashList.Count < 48) // for 32-byte key and 16-byte iv
{
preHashLength = currentHash.Length + data.Length + ((salt != null) ? salt.Length : 0);
preHash = new byte[preHashLength];
System.Buffer.BlockCopy(currentHash, 0, preHash, 0, currentHash.Length);
System.Buffer.BlockCopy(data, 0, preHash, currentHash.Length, data.Length);
if (salt != null)
System.Buffer.BlockCopy(salt, 0, preHash, currentHash.Length + data.Length, salt.Length);
currentHash = hash.ComputeHash(preHash);
for (int i = 1; i < count; i++)
{
currentHash = hash.ComputeHash(currentHash);
}
hashList.AddRange(currentHash);
}
hash.Clear();
key = new byte[32];
iv = new byte[16];
hashList.CopyTo(0, key, 0, 32);
hashList.CopyTo(32, iv, 0, 16);
}
static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged cipher = new RijndaelManaged())
{
cipher.Key = Key;
cipher.IV = IV;
//cipher.Mode = CipherMode.CBC;
//cipher.Padding = PaddingMode.PKCS7;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = cipher.CreateEncryptor(cipher.Key, cipher.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (var cipher = new RijndaelManaged())
{
cipher.Key = Key;
cipher.IV = IV;
//cipher.Mode = CipherMode.CBC;
//cipher.Padding = PaddingMode.PKCS7;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = cipher.CreateDecryptor(cipher.Key, cipher.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
}
注意:还有一些与此相关的代码......
这些分别不在nuget
或npm
中,因为它们真的不属于那里……主要是为了想法和引用。我确实需要更好地冲洗 Node 端,以便匹配。
关于c# - NodeJS 和 C# 中的 AES256 加密/解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18502375/
我只想使用这 3 种模式从 openSSL 测试 AES: key 长度为 128,192 和 256,但我的解密文本与我的输入不同,我不知道为什么。此外,当我传递一个巨大的输入长度(比如说 1024
最近我终于(在 stackoverflow 的用户@WhozCraig 的帮助下)开始在 CBC 模式下使用 AES。现在,我想做完全相同的事情,但使用 AES IGE。我查看了 openssl-1.
网络设备已经配置了 snmpv3 用户,使用 AES192 作为隐私协议(protocol)。但是当执行以下命令时 snmpwalk -v3 -l authPriv -u user -a SHA -A
我在 c# 中使用 AES 算法进行加密和解密。我使用 AesCryptoServiceProvider 类进行加密和解密。 这是我在代码中的设置 AesCryptoServiceProvider r
我正在尝试使用具有不同 key 大小的 openssl 的 AES_decrypt 函数来解密密文。我能够成功解密 key 大小 = 128 的消息。这是我的代码 mydecrypt.c #inclu
如何在 AES-128、AES-192 和 AES-256 之间切换。我目前的实现仅使用 AES-128 Cipher cipher = Cipher.getInstance("AES/CBC/NoP
我的问题是我想在一个线图上叠加一个散点图,这两个图的颜色随着一个变量而变化。我只想保留一种颜色的图例。如果我使用 scale_colour_discrete(guide = "none") 它们都将消
我想用 C# 编写一个可以打开 KeePass 的程序1.x kdb 文件。我下载了源代码并尝试移植密码数据库读取功能。数据库内容已加密。加密 key 通过以下方式获得: 用户输入密码; 计算密码的
我只想将ruby代码迁移到Java 这是我的 ruby 代码 require 'openssl' require 'base64' key = '7c54367a45b37a192abc2cd7f45
我正在使用 AES 的 PyCrypto 实现,并且我正在尝试使用 24 字节 key 加密一些文本(24 字节)。 aes_ecb = AES.new('\x00'*24, AES.MODE_ECB
有人比较这些加密算法的优缺点吗? 最佳答案 使用 AES。 更多详细信息: DES 是七十年代的旧“数据加密标准”。它的 key 大小对于适当的安全性而言太短(56 个有效位;这可以被暴力破解,如 m
我在 iOS 中加密一个 NSString,编码和解码都很好: NSString *stringtoEncrypt = @"This string is to be encrypted"; NSStr
我正在尝试使用 nVidia CUDA 在 CTR 模式下实现 AES-256。我已经成功地为 key 扩展编写了 CPU 代码,现在我需要实现实际的 AES-256 算法。根据维基百科,我见过一些代
我正在 Contiki OS 中研究 AES 安全性。我有 AES 库,它支持两种类型的加密/解密: 即时 固定键 在即时中,当我使用 key 加密数据时,会生成新 key 和加密数据。这个新生成的
关于 AES 有很多问题,但我有以下问题。我目前正在使用以下 AES 实现来加密数据 byte [] PRFkey = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
有没有人一起比较这些加密算法的优缺点? 最佳答案 使用 AES。 更多细节: DES 是七十年代的旧“数据加密标准”。它的 key 大小对于适当的安全性来说太短了(56 位有效位;这可以被强制执行,正
我的团队需要开发一种解决方案,以在用 Java 编写的 Android 应用程序的上下文中加密二进制数据(存储为 byte[])。加密后的数据将通过多种方式传输和存储,在此过程中不排除出现数据损坏的情
我在客户端使用 CryptoJS AES 算法加密文本,我在服务器端用 java 解密它,但出现异常。 JS代码: var encrypted = CryptoJS.AES.encrypt("Mess
我之所以问这个问题,是因为 2 天来我已经阅读了很多关于加密 AES 加密的帖子,就在我以为我明白了的时候,我意识到我根本没有明白。 这篇文章是最接近我的问题的,我有完全相同的问题但没有得到解答: C
我想知道 AES 加密后的数据大小,这样我就可以避免缓冲我的 AES 后数据(在磁盘或内存上)主要是为了知道大小。 我使用 128 位 AES 和 javax.crypto.Cipher 和 java
我是一名优秀的程序员,十分优秀!