【问题标题】:Having a C# encryption decryption methods , wanted there copy in JAVA有C#加密解密方法,想在JAVA里面复制
【发布时间】:2015-06-04 07:55:22
【问题描述】:
private static string Encrypt(string plainText)
{
    byte[] keyBytes = Encoding.UTF8.GetBytes(_secretKey);
    byte[] hashedKeyBytes = new SHA256CryptoServiceProvider().ComputeHash(keyBytes);
    var secretKeyHashString = string.Concat(hashedKeyBytes.Select(hb => hb.ToString("x2")));
    byte[] cryptoKeyHash = new SHA256CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(secretKeyHashString));
    byte[] cryptoKey = cryptoKeyHash.Take(16).ToArray();

    var aes = new AesCryptoServiceProvider()
    {
        Padding = PaddingMode.PKCS7,
        Key = cryptoKey,
        Mode = CipherMode.CBC,
        IV = _initialisationVector
    };

    RijndaelManaged aesEnc = new RijndaelManaged();
    byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

    var encryptor = aes.CreateEncryptor();
    byte[] encryptedBytes = encryptor.TransformFinalBlock(plainTextBytes, 0, plainTextBytes.Length);
    var encryptedString = Convert.ToBase64String(encryptedBytes);

    return encryptedString;
}

private static string Decrypt(string encryptedText)
{
    byte[] keyBytes = Encoding.UTF8.GetBytes(_secretKey);
    byte[] hashedKeyBytes = new SHA256CryptoServiceProvider().ComputeHash(keyBytes);
    var secretKeyHashString = string.Concat(hashedKeyBytes.Select(hb => hb.ToString("x2")));
    byte[] cryptoKeyHash = new SHA256CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(secretKeyHashString));
    byte[] cryptoKey = cryptoKeyHash.Take(16).ToArray();

    byte[] initialisationVector = { 0, 133, 36, 86, 84, 150, 188, 164, 28, 210, 112, 158, 141, 87, 11, 227 };
    var aes = new AesCryptoServiceProvider()
    {
        Padding = PaddingMode.PKCS7,
        Key = cryptoKey,
        Mode = CipherMode.CBC,
        IV = _initialisationVector
    };
    var decryptor = aes.CreateDecryptor();

    var encryptedBytes = Convert.FromBase64String(encryptedText);
    var decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
    var decryptedString = Encoding.UTF8.GetString(decryptedBytes);

    return decryptedString;
}

【问题讨论】:

    标签: java encryption aes sha256


    【解决方案1】:

    【讨论】:

    • 嗨 Dhaval,感谢您的回答!
    • 由于这些方法是客户端给出的,我们必须在JAVA中使用相同的方法。还有一些代码中的初始化向量,我没有得到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    相关资源
    最近更新 更多