Java密码和php mcrypt_encrypt(带有ECB填充的BLOWFISH算法)

时间:2012-09-25 21:33:48

标签: java php encryption encoding cryptography

这是我的问题,我有从java(jsp)接口创建的用户帐户,它使用Blowfish / ECB / PKCS5Padding来加密存储在数据库中的密码。现在,我试图从一个不同的应用程序进行身份验证,该应用程序是使用从java(jsp)前端创建的用户帐户在PHP中开发的,但是当我尝试比较加密后从java end和php返回的值时出来是不同的。

JAVA CODE:

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

JAVA OUTPUT:

    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==

请帮我解决这个问题。

感谢:)

1 个答案:

答案 0 :(得分:0)

首先,您可能希望在两个系统上以十六进制编码您的字节,这使得比较更加容易。

其次,您无法控制如何在字符串之间转换为字节数组编码(反之亦然)。这称为字符编码。在Java中,如果不指定字符编码,则不应使用String.getBytes()方法。

[B@1ea5671结果只是字节数组对象实例的标识。您无法直接在Java中打印出字节数组。