我已经制作了这个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文件

最佳答案

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


试试这个代码。它可以encryptdecrypt。我假设您知道如何在Java中进行编码。

10-07 15:38