我已经制作了这个PHP加密脚本。现在我想知道如何用Java完成。我正在考虑放弃它,并在Javascript中编码,以便它可以在两种语言中使用。遗憾的是,这不是我想要的。我怎么能用Java做到这一点?
<?php
$encrypted = encrypt("Hello goodbye", "Pizza");
$decrypted = decrypt($encrypted, "Pizza");
echo $encrypted;
echo "<br/>";
echo $decrypted;
function encrypt($string, $key) {
$result = '';
for($i=0; $i<strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)+ord($keychar));
$result.=$char;
}
return base64_encode($result);
}
function decrypt($string, $key) {
$result = '';
$string = base64_decode($string);
for($i=0; $i<strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)-ord($keychar));
$result.=$char;
}
return $result;
}
?>
我不是要求为我写一些代码(但它会很棒),但我希望得到帮助或者朝着正确的方向努力
修改 我不想通过Java发布和获取PHP文件
答案 0 :(得分:1)
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class AdvanceEncryptionSecurity {
private static final String ALGORITHM = "AES";
private static final int ITERATIONS = 2;
private static final byte[] keyValue = new byte[] { 'P', 'R', 'S', 'a', 'n', 'd', 'A', 'P', 'F', 'A', 'A', 'l', 'l', 'i', 'e', 'd' };
private static String salt = "prs and pfa";
public static String encrypt(String value) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key);
String valueToEnc = null;
String eValue = value;
for (int i = 0; i < ITERATIONS; i++) {
valueToEnc = salt + eValue;
byte[] encValue = c.doFinal(valueToEnc.getBytes());
eValue = new BASE64Encoder().encode(encValue);
}
return eValue;
}
public static String decrypt(String value) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
String dValue = null;
String valueToDecrypt = value;
for (int i = 0; i < ITERATIONS; i++) {
byte[] decordedValue = new BASE64Decoder().decodeBuffer(valueToDecrypt);
byte[] decValue = c.doFinal(decordedValue);
dValue = new String(decValue).substring(salt.length());
valueToDecrypt = dValue;
}
return dValue;
}
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(keyValue, ALGORITHM);
return key;
}
}
试试这段代码。它可以encrypt
和decrypt
。我假设你知道如何在java中编码。
答案 1 :(得分:0)
这个GitHub存储库解决了它:Android PHP Encrypt Decrypt