c# - 使用 AesCryptoServiceProvider 在没有 IV 的情况下解密

标签 c# .net encryption aes

我编写了一个使用 AES 加密的 BlackBerry 应用程序。我正在尝试使用 C# 中的 AesCryptoServiceProvider 对此进行解密。

BlackBerry 代码似乎没有使用 IV,这意味着我没有任何东西可以传递给 AesCryptoServiceProvider。

我是否可以在没有 IV 的情况下解密 AES,如果可以,怎么做?

最佳答案

阅读黑莓 java 加密文档,看来您不应该直接使用 AESEncryptionEngine。如果你直接使用它,你最终会得到(我假设)ECB 模式,这会导致企鹅图像的以下加密。不要这样做。

Bad Encryption 相反,似乎要使用某种安全的操作模式,您需要实际使用基本 AESEncrypt/解密引擎的包装器。你想使用 CBCEncryptionEngine去做这个。这是来自 here 的一些示例代码.请注意,IV 在创建时是随机的,因此您无需设置它或担心重复使用。只需在此处将 DES 替换为 AES 即可。

// sampleDESCBCEncryption
private static int sampleDESCBCEncryption( 
    byte[] secretKey, byte[] initVector, byte[] plainText, byte[] cipherText, int
    dataLength ) 
    throws CryptoException, IOException
{
    // Create a new DES key based on the 8 bytes in the secretKey array
    DESKey key = new DESKey( secretKey );

    // Create a new initialization vector using the 8 bytes in initVector
    InitializationVector iv = new InitializationVector( initVector );

    // Create a new byte array output stream for use in encryption
    NoCopyByteArrayOutputStream out = new NoCopyByteArrayOutputStream();

    // Create a new instance of a BlockEncryptor passing in an instance of a CBC encryptor engine
    // (containing an instance of a DES encryptor engine), the initialization vector, and the
    // output stream
    BlockEncryptor cryptoStream = new BlockEncryptor( 
        new CBCEncryptorEngine( new DESEncryptorEngine( key ), iv ), out );

    // Write dataLength bytes from plainText to the CFB encryptor stream
    cryptoStream.write( plainText, 0, dataLength );
    cryptoStream.close();

    // Now copy the encrypted bytes from out into cipherText and return the length
    int finalLength = out.size();
    System.arraycopy( out.getByteArray(), 0, cipherText, 0, finalLength );
    return finalLength;
}    

关于c# - 使用 AesCryptoServiceProvider 在没有 IV 的情况下解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9700215/

相关文章:

c# - 使用Nest(Elasticsearch)进行方面搜索

c# - 没有组元素的列表的 CollectionDataContractAttribute

c# - 在 async/await 上阻塞主线程

c# - 使用 System.IO.File.Move 时自动创建文件夹

java - java中基于密码的加密/解密: fails to decrypt the file even though the password is identical

php - 密码哈希无法登录 codeigniter

c# - 从另一个服务停止服务

c# - 有没有办法直接查询 Entity Framework Core 使用的内存数据库?

.net - 无需注册即可创建自定义文化

ruby-on-rails - 如何让 Ruby 读取 .cer 公共(public) ssl key ?