这是我的问题,我有从 java(jsp) 接口创建的用户帐户,该接口使用 Blowfish/ECB/PKCS5Padding 加密密码以存储在数据库中。现在,我正在尝试使用从 java(jsp) 前端创建的用户帐户从 PHP 开发的不同应用程序进行身份验证,但是当我尝试比较加密后从 java 端和 php 返回的值时,它们出来不一样。
JAVA代码:
import java.io.*;
import java.util.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.Provider;
import java.security.Security;
public class Test
{
public static byte[] raw =null;
public static SecretKeySpec skeySpec;
public static Cipher cipher;
public static void main(String ags[]) throws Exception
{
byte[] key={1,2,3,4,5,6,7};
skeySpec = new SecretKeySpec(key, "Blowfish");
System.out.println("KEY : "+bytesToString(skeySpec.getEncoded()));
String cipherInstName = "Blowfish/ECB/PKCS5Padding";
cipher = Cipher.getInstance(cipherInstName);
cipher.init(Cipher.ENCRYPT_MODE,skeySpec);
byte[] encrypted = cipher.doFinal(("asdfgh").getBytes());
System.out.println("PLAIN TEXT : "+("asdfgh").getBytes());
System.out.println("ENCRYPTED TEXT : "+bytesToString(encrypted));
}
private static String bytesToString(byte [] value)
{
StringBuffer retVal = new StringBuffer();
for(int i=0; i<value.length; i++)
{
retVal.append(value[i]+":");
}
int inx = retVal.toString().lastIndexOf(":");
retVal= new StringBuffer(retVal.toString().substring(0,inx));
return retVal.toString();
}
}
爪哇输出:
KEY : 1:2:3:4:5:6:7
PLAIN TEXT : [B@1ea5671
ENCRYPTED TEXT : 81:102:-114:102:82:80:83:-123
PHP代码:
function pkcs5_pad($text,$blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text.str_repeat(chr($pad),$pad);
}
function pkcs5_unpad($text)
{
$pad = ord($text{strlen($text)-1});
if ($pad > strlen($text)) return false;
if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
return substr($text, 0, -1 * $pad);
}
$blockSize = mcrypt_get_block_size(MCRYPT_BLOWFISH,MCRYPT_MODE_ECB);
$padded = pkcs5_pad("asdfgh",$blockSize);
$key="1:2:3:4:5:6:7";
echo "<br/>";
//$cipher = mcrypt_ecb(MCRYPT_BLOWFISH,$key, $padded, MCRYPT_ENCRYPT);
$cipher = mcrypt_encrypt("blowfish",$key,$padded,"ecb");
echo "ENCRYPTED TEXT : ".base64_encode($cipher);
PHP 输出:
ENCRYPTED TEXT : draOlOiLFMs/Y+x+7mOhZw==
请帮助我解决这个问题。
谢谢:)