簡體   English   中英

Android中的Base64加密

[英]Base64 encryption in android

以下是用於加密和解密的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端解密數據的方式進行加密。

如果您向openssl_encrypt查詢PHP文檔,則會注意到,未設置任何選項,該函數將以十六進制字符串而不是原始二進制數據形式返回加密結果。

在Java代碼中,您使用base64編碼了加密的實際二進制結果(應該如此)。 在您的PHP代碼中,您正在對base64編碼的十六進制字符串加密結果,而您不應該這樣做。 您需要使用OPENSSL_RAW_DATA

另請注意,您的代碼存在許多安全問題。 使用固定的IV是更大的方法之一,請不要這樣做。 我不建議您使用生產環境中的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM