相关疑难解决方法(0)

Java 256位AES密码加密

我需要实现256位AES加密,但我在网上找到的所有示例都使用"KeyGenerator"生成256位密钥,但我想使用自己的密码.如何创建自己的密钥?我已经尝试将其填充为256位,但后来我得到一个错误,说密钥太长了.我确实安装了无限管辖区补丁,所以那不是问题:)

IE浏览器.KeyGenerator看起来像这样......

// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available

// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
Run Code Online (Sandbox Code Playgroud)

代码来自这里

编辑

我实际上是将密码填充到256个字节,而不是位,这太长了.以下是我现在使用的一些代码,我对此有更多的经验.

byte[] key = null; // TODO
byte[] input = null; // TODO
byte[] output = null;
SecretKeySpec keySpec = null;
keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
output = cipher.doFinal(input)
Run Code Online (Sandbox Code Playgroud)

您需要自己做的"TODO"位:-)

java encryption passwords cryptography aes

381
推荐指数
6
解决办法
52万
查看次数

对称加密(AES):保存IV和Salt以及加密数据是否安全且正确?

在使用对称加密算法(在本例中为AES)加密和解密数据时,我试图理解如何处理和管理启动向量和盐(适用时).

我从不同的SO线程和各种其他网站推断出,IV或盐都不需要保密,只是为了防御密码分析攻击,例如蛮力攻击.考虑到这一点,我认为将伪随机IV与加密数据一起存储是可行的.我问的是我使用的方法是否合适,而且,我是否应该以同样的方式处理我目前的硬编码盐?那就是将它写在IV旁边的内存流中

我的代码:

private const ushort ITERATIONS = 300;
private static readonly byte[] SALT = new byte[] { 0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22,  0x3c };

private static byte[] CreateKey(string password, int keySize)
{
    DeriveBytes derivedKey = new Rfc2898DeriveBytes(password, SALT, ITERATIONS);
    return derivedKey.GetBytes(keySize >> 3);
}

public static byte[] Encrypt(byte[] data, string password)
{
    byte[] encryptedData = null;
    using (AesCryptoServiceProvider provider = new AesCryptoServiceProvider())
    {
        provider.GenerateIV();
        provider.Key = CreateKey(password, provider.KeySize);
        provider.Mode …
Run Code Online (Sandbox Code Playgroud)

c# encryption cryptography encryption-symmetric

22
推荐指数
2
解决办法
1万
查看次数