c# - 如何在 c# 中使用 AES 128 位加密字符串?
问题描述
我正在使用 oracle Database12c 在 asp.net 中处理 webapplication 我使用 aes128 存储过程来加密密码 这里是进行加密的过程
DECLARE
l_user_id test.username%TYPE := 'SCOTT';
l_user_psw VARCHAR2 (2000) := 'mypassword123';
l_key VARCHAR2 (2000) := '1234567890999999';
l_mod NUMBER
:= DBMS_CRYPTO.ENCRYPT_AES128
+ DBMS_CRYPTO.CHAIN_CBC
+ DBMS_CRYPTO.PAD_PKCS5;
l_enc RAW (2000);
BEGIN
l_user_psw :=
DBMS_CRYPTO.encrypt (UTL_I18N.string_to_raw (l_user_psw, 'AR8MSWIN1256'),
l_mod,
UTL_I18N.string_to_raw (l_key, 'AR8MSWIN1256'));
DBMS_OUTPUT.put_line ('Encrypted=' || l_user_psw);
INSERT INTO test VALUES (l_user_id, l_user_psw);
dbms_output.put_line('done');
COMMIT;
END;
/
最后的结果是
132BEDB1C2CDD8F23B5A619412C27B60
现在我想在 c# 中制作相同的 Aes 我知道我可以从 c# 调用存储过程并获得相同的结果,但是出于安全原因我想使用 c# 制作它我尝试了很多方法但最终得到了不同的结果!我需要帮助!
解决方案
由于我感到慷慨,我将为您提供解决方案:
public static string EncryptPassword(string key, string password)
{
// Your current code uses WIN1256 encoding for converting
// your strings to bytes, so we'll use that here
var encoding = System.Text.Encoding.GetEncoding(1256);
byte[] passwordBytes = encoding.GetBytes(password);
byte[] keyBytes = encoding.GetBytes(key);
using (var aes = AesManaged.Create())
{
// Set up the algorithm
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.CBC;
aes.Key = keyBytes;
aes.BlockSize = 128; // AES-128
// You don't specify an IV in your procedure, so we
// need to zero it
aes.IV = new byte[16];
// Create a memorystream to store the result
using (var ms = new MemoryStream())
{
// create an encryptor transform, and wrap the memorystream in a cryptostream
using (var transform = aes.CreateEncryptor())
using (var cs = new CryptoStream(ms, transform, CryptoStreamMode.Write))
{
// write the password bytes
cs.Write(passwordBytes, 0, passwordBytes.Length);
}
// get the encrypted bytes and format it as a hex string and then return it
return BitConverter.ToString(ms.ToArray()).Replace("-", string.Empty);
}
}
}
推荐阅读
- javascript - 父子组件中的 onclick 事件问题
- hyperledger-fabric - fabric-sdk-node 无法检索现有用户的上下文
- meshlab - MeshLab - TIN 上采样
- node.js - 异步 for 循环 Node.js
- python - FileNotFoundError:将 excel 文件推送到 sftp 服务器时
- matlab - 如何解决 Matlab 中的“内存不足错误”?
- javascript - 使用 new 运算符时是否可以进行依赖注入?
- python - 如何将少量对象分配给一个用户
- python - 如何 cythonize 全局 __builtin__ 对象?
- python - Spark 替代 scipy stats norm pdf 函数