我使用sha-512算法和盐加密了数据,我想解密这些数据,请问有人可以告诉我如何使用Java对其进行解码。
谢谢。
谢谢。
SHA-512是一种密码哈希函数。密码哈希函数是单向的,你可以对数据块进行哈希计算,但当你只有哈希值时,无法还原原始数据。因此,你不能解密哈希代码以获取原始数据。
密码哈希函数通常用于在数据库中存储密码。要检查用户输入的密码是否正确,你可能会想到“好的,我必须解密数据库中的密码并检查它是否等于用户输入的密码”。然而,这不是正确的做法。
相反,你需要对用户输入的密码进行哈希处理,并将该哈希值与数据库中存储的哈希值进行比较。如果哈希值相同,则用户输入了正确的密码。你不需要“解密”哈希值。
SHa 512不是加密算法。哈希算法旨在设计为仅能以单向方式验证数据的完整性。
简而言之:不,您无法“解密”任何哈希算法。
String plainText = "text" + "salt";
MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
byte[] hash = messageDigest.digest( plainText.getBytes() );
System.out.println("Result: " + new String(hash));
如果您知道可能的明文值,可以找到匹配的哈希值。然而,如果没有关于原始数据的线索,暴力破解需要花费相当长的时间。
如何使用SHA512代替MD5
这里是MD5代码
public class RijndaelSimple
{
public static string Decrypt
(
string cipherText,
string passPhrase,
string saltValue,
string hashAlgorithm,
int passwordIterations,
string initVector,
int keySize
)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes password = new PasswordDeriveBytes
(
passPhrase,
saltValueBytes,
hashAlgorithm,
passwordIterations
);
byte[] keyBytes = password.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor
(
keyBytes,
initVectorBytes
);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream
(
memoryStream,
decryptor,
CryptoStreamMode.Read
);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read
(
plainTextBytes,
0,
plainTextBytes.Length
);
memoryStream.Close();
cryptoStream.Close();
string plainText = Encoding.UTF8.GetString
(
plainTextBytes,
0,
decryptedByteCount
);
return plainText;
}
}
public class RijndaelSimpleTest
{
[STAThread]
static void Main(string[] args)
{
string plainText = "Hello, World!"; // original plaintext
string passPhrase = "Pas5pr@se"; // can be any string
string saltValue = "kplcs@1tValue"; // can be any string
string hashAlgorithm = "SHA1"; // can be "MD5"
int passwordIterations = 2; // can be any number
string initVector = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
int keySize = 256; // can be 192 or 128
Console.WriteLine(String.Format("Plaintext : {0}", plainText));
string cipherText = RijndaelSimple.Encrypt
(
plainText,
passPhrase,
saltValue,
hashAlgorithm,
passwordIterations,
initVector,
keySize
);
Console.WriteLine(String.Format("Encrypted : {0}", cipherText));
plainText = RijndaelSimple.Decrypt
(
cipherText,
passPhrase,
saltValue,
hashAlgorithm,
passwordIterations,
initVector,
keySize
);
Console.WriteLine(String.Format("Decrypted : {0}", plainText));}}