我在 ASP 中有一个代码,但我不知道在 php 中加密并比较加密的密码。
我的图书馆是:
using System.Security.Cryptography;
// Encrypt a string into a string using a password
// Uses Encrypt(byte[], byte[], byte[])
public string Encrypt(string clearText, string Password)
{
// First we need to turn the input string into a byte array.
byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
// Then, we need to turn the password into Key and IV
// We are using salt to make it harder to guess our key using a dictionary attack -
// trying to guess a password by enumerating all possible words.
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
// Now get the key/IV and do the encryption using the function that accepts byte arrays.
// Using PasswordDeriveBytes object we are first getting 32 bytes for the Key
// (the default Rijndael key length is 256bit = 32bytes) and then 16 bytes for the IV.
// IV should always be the block size, which is by default 16 bytes (128 bit) for Rijndael.
// If you are using DES/TripleDES/RC2 the block size is 8 bytes and so should be the IV size.
// You can also read KeySize/BlockSize properties off the algorithm to find out the sizes.
byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
// Now we need to turn the resulting byte array into a string.
// A common mistake would be to use an Encoding class for that. It does not work
// because not all byte values can be represented by characters.
// We are going to be using Base64 encoding that is designed exactly for what we are
// trying to do.
return Convert.ToBase64String(encryptedData);
}
和php代码是:
function fnEncrypt($Word, $key){
$iv = mcrypt_create_iv( mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND );
if (strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != 22) return false;
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $Word . md5($Word), MCRYPT_MODE_CBC, $iv));
return $iv_base64 . $encrypted;
}
或者我尝试在 php 中使用此代码:
function Encrypt($pass, $salt){
$derived = PBKDF1($pass, $salt, 100, 32);
$key = bin2hex(substr($derived, 0, 32));
$iv = bin2hex(substr($derived, 32, 16));
return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $pass, MCRYPT_MODE_CBC, $iv);
}
function PBKDF1($pass, $salt, $count, $dklen)
{
$t = sha1($pass.$salt);
for($i=1; $i <= $count; $i++)
{
$t = sha1($t);
}
$t = substr($t,0,$dklen-1);
return $t;
}
但不工作,我希望我能帮忙。
对不起我的英语不好