【问题标题】:Base64 encryption in androidandroid中的Base64加密
【发布时间】:2018-05-06 00:03:47
【问题描述】:

下面是加解密的PHP代码。我想在我的 android 应用程序中做类似的事情

    <?php
function my_simple_crypt( $string, $action = 'e' ) {
   // you may change these values to your own
   $secret_key = '8D9479FA674EF929B7AEEC8CD7593';
   $secret_iv = '6CA78EDF24D9B258E9297A4EE251A';

   $output = false;
   $encrypt_method = "AES-256-CBC";
   $key = hash( 'sha256', $secret_key );
   $iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );

   if( $action == 'e' ) {
       $output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
   }
   else if( $action == 'd' ){
       $output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv );
   }

   return $output;
}

echo my_simple_crypt("token=RAJSHEKAR_9d979115-4a59-486d-b12a-ff0f2c36344e&loginName=rajshekar&clinicUserId=788");


?>

我已经完成了哈希生成。

  public String computeHash(String input)
            throws NoSuchAlgorithmException, UnsupportedEncodingException
    {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(
                input.getBytes(StandardCharsets.UTF_8));
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if(hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        System.out.println("hexString::"+hexString.toString());
        return hexString.toString();
    }

以下是加密代码,但我没有得到正确的加密输出。

 public static String encrypt(String key, String iv, String data) {
        try {
            IvParameterSpec initVector = new IvParameterSpec(iv.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance(WebviewActivity.CIPHER_NAME);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, initVector);

            byte[] encryptedData = cipher.doFinal((data.getBytes()));

            String base64_EncryptedData = Base64.encodeToString(encryptedData,Base64.DEFAULT);

            return base64_EncryptedData;

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

我想以一种可以在 php 端解密数据的方式进行加密。

【问题讨论】:

  • Base64 不是一种加密方法,也不是一种安全传输数据的方法。

标签: java php android encryption


【解决方案1】:

如果您查阅openssl_encrypt 的 PHP 文档,您会注意到,如果未设置任何选项,该函数将返回加密结果作为十六进制字符串,而不是作为原始二进制数据。

在您的 Java 代码中,您正在对加密的实际二进制结果进行 base64 编码(您应该这样做)。在您的 PHP 代码中,您对加密的十六进制字符串结果进行了 base64 编码,您不应该这样做。您需要使用OPENSSL_RAW_DATA

另请注意,您的代码存在许多安全问题。使用固定 IV 是较大的一种,不要这样做。我不建议在生产环境中使用您的代码。

【讨论】:

  • 我将代码更改如下 $output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, OPENSSL_RAW_DATA, $iv ) );加密后的输出还是和java不一样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多