所以我在php服务器上加密了一个字符串。
encrypt("http://google.com", "happy");
function encrypt($str, $key)
{
$block = mcrypt_get_block_size('des', 'ecb');
$pad = $block - (strlen($str) % $block);
$str .= str_repeat(chr($pad), $pad);
return mcrypt_encrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
}
顺便说一句,这会返回一些奇怪的字符串。。。我期待着字母和数字:ZöÞ ÔP»8
回到Java,我需要用密钥解密这个字符串。
这可能有助于java:中的MCrypt
http://www.java2s.com/Open-Source/Java-Document/EJB-Server/resin-4.0.7/com/caucho/quercus/lib/mcrypt/Mcrypt.java.htm
另一个链接:
http://www.kanatorn.info/2011/11/07/aes-encrypt-decrypt-between-java-php/
我不喜欢mcrypt,但通过加密运行ASCII明文并不总是产生ASCII密文。当你试图将生成的加密密文解释为ASCII或unicode文本时,很可能会将其转换为"奇怪的字符串"。
首先,确保它不是单向加密。其次,php中使用的算法和参数以及java
我认为这会很有用。请注意,字符集是UTF-8。
public class Foo {
public static void main(String[] args) {
try {
String cipherSpec = "DES/ECB/NoPadding";
Cipher cipher = Cipher.getInstance(cipherSpec);
int blockSize = cipher.getBlockSize();
String keyText = "happy";
Key key = new SecretKeySpec(padRight(keyText, blockSize).getBytes("UTF-8"), "DES");
String input = "http://google.com";
input = padRight(input, input.length() + blockSize - (input.length() % blockSize));
// encrypt
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherText = cipher.doFinal(input.getBytes(CHARSET));
System.out.println("'ncipher text: ");
System.out.println(new String(cipherText, CHARSET));
// decrypt
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainText = cipher.doFinal(cipherText);
System.out.println("'nplain text: ");
System.out.println(new String(plainText, CHARSET));
} catch (Exception e) {
e.printStackTrace();
}
}
final static String CHARSET = "UTF-8";
static String padRight(String s, int n) {
return String.format("%1$-" + n + "s", s);
}
}