http://www.php.net/manual/en/ref.mcrypt.php To have the same result in Java and PHP with the BouncyCastle library : php function encrypt($str, $operation, $key) { $ret = ''; $key = pack('H*', $key); if (strtoupper($operation) == 'DECODE')
http://www.php.net/manual/en/ref.mcrypt.php
To have the same result in Java and PHP with the BouncyCastle library :
php
function encrypt($str, $operation, $key)
{
$ret = '';
$key = pack('H*', $key);
if (strtoupper($operation) == 'DECODE') {
$str = pack('H*', $str);
$ret = mcrypt_ecb(MCRYPT_BLOWFISH, $key, $str, MCRYPT_DECRYPT);
} else {
$ret = mcrypt_ecb(MCRYPT_BLOWFISH, $key, $str, MCRYPT_ENCRYPT);
$ret = bin2hex($ret);
}
return $ret;
}
java
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
public class tester {
public static void crypter(String password) {
try {
// -- Install jar "bcprov-jdk14-135.jar" in /jre/lib/ext/
//
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("Blowfish/ECB/ZeroBytePadding");
// -- Substring is used to have no problem with key length
SecretKeySpec keySpec = new SecretKeySpec(password.substring(0,8).getBytes(), "Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] outText = cipher.doFinal(password.getBytes());
System.out.println(asHex(outText));
}
catch (Exception e) {
e.printStackTrace();
}
}
public static String asHex (byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
public static void main(String[] args) {
try {
crypter("password");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
本文原创发布php中文网,转载请注明出处,感谢您的尊重!