代码之家  ›  专栏  ›  技术社区  ›  DJ'

我需要两个函数来加密PHP中的一些数据,并在Java中正确地解密它。

  •  0
  • DJ'  · 技术社区  · 15 年前

    我需要两个功能。我想以XML格式将数据从我的网站传输到我的服务器。现在在我的服务器上,我想做一个加密数据并把它放在XML中的函数,以及Java中的另一个函数来解密它。

    请告诉我是否有任何预先定义的功能,或者您能抽出5分钟吗?

    3 回复  |  直到 15 年前
        1
  •  3
  •   shamittomar    15 年前

    嗯,你可以用任何加密 mcrypt 函数。在AES 128中加密的一个示例:

      $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
      $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
      $key = "Put your secret key here";
      $text = "<xml>This is your XML text</xml>";
    
      //encrypting now with RIJNDAEL 128 encryption.
      $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_ECB, $iv);
    
      //Display encrypted content
      echo $crypttext;
    

    对于解密,使用这个代码(我不是Java PRO,所以可能有一些bug):

    package org.kamal.crypto;
    
    import java.security.*;
    import java.security.spec.InvalidKeySpecException;
    import javax.crypto.Cipher; 
    import javax.crypto.spec.SecretKeySpec;
    import sun.misc.*;
    
    public class SimpleProtector
    {
        private static final String ALGORITHM = "AES";
        private static final byte[] keyValue = 
            new byte[] { 'P', 'u', 't', ' ', 'Y', 'o', 'u', 'r', ' ', 'S', 'e', 'c', 'r', 'e', 't', ' ', 'K', 'e', 'y', '', 'H', 'e', 'r', 'e'};
    
        public static String decrypt(String encryptedValue) throws Exception {
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.DECRYPT_MODE, key);
            byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedValue);
            byte[] decValue = c.doFinal(decordedValue);
            String decryptedValue = new String(decValue);
            return decryptedValue;
        }
    
        private static Key generateKey() throws Exception {
            Key key = new SecretKeySpec(keyValue, ALGORITHM);
            // SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            // key = keyFactory.generateSecret(new DESKeySpec(keyValue));
            return key;
        }
    }
    
        2
  •  1
  •   Community CDub    8 年前

    在这里重新发明轮子毫无意义。使用ssl,这是一个https请求所涉及的。你可以通过卷曲来完成。

    CURL内置PHP,还有Java版本 http://php.net/manual/en/book.curl.php

    cURL equivalent in JAVA

    希望有帮助。

        3
  •  -1
  •   cbednarski    15 年前

    你查过了吗 JSON ?

    它不是加密的,但它是在不同的程序和语言之间来回传递数据的一种简单方法。

    推荐文章