拥有C#加密解密方法,希望在JAVA中有副本

时间:2015-06-04 07:55:22

标签: java encryption aes sha256

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;
}

1 个答案:

答案 0 :(得分:0)