我无法在Android中将base64编码的字符串转换为十六进制字符串?

时间:2018-10-12 10:32:34

标签: android base64 aes

我正在使用AES(Rijndael)加密方法来加密字符串。使用的转换为ECB_PKCS5PADDING。它将返回一个base64编码的字符串。我已经使用base64对该字符串进行了解码,并使用一个函数将其转换为hex。代码片段附在下面。

private void encrptString() 
 {
    sample = "<xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    String encrypt = Encoder.BuilderAES()
            .message(sample)
            .method(AES.Method.AES_ECB_PKCS5PADDING)
            .key("xxxxxxxxxxxxxx")
            .keySize(AES.Key.SIZE_128)
            .encrypt();

    System.out.println("encrypt"+encrypt);

    String stringFromBase = new String(Base64.decode(encrypt,Base64.DEFAULT));
    System.out.println("base64"+stringFromBase.trim());



   String hex= null;
   try {
       hex = toHex(stringFromBase);
   } catch (UnsupportedEncodingException e) {
       e.printStackTrace();
   }
   Toast.makeText(this, hex, Toast.LENGTH_SHORT).show();
   System.out.println("hex"+hex.trim());


   }

public String toHex(String arg) throws UnsupportedEncodingException {
    return String.format("%040x", new BigInteger(1, arg.getBytes("UTF-8")));


}

base64输入字符串:

  

O3Kmyftikp0lY / 8SVWMiLFCn9sdQX7HauqdLZXcE + jkVcZH7kfPD /   jSLIC2wlP1iQTaiynoaW8A7L1INEYunkmCWT2eVwumwouHVT7d5Kq   / sqEcB9 / 9pyyAuSjrQxtCgJlHm7dlvt0lVEHD2pHnEAhZTRtuuy6b   8MNI7W4jLn + / ZNEqZxdJll26a52D7ceFv

预期输出:

  

3b72a6c9fb62929d2563ff125563222c50a7f6c7505fb1dabaa74b657704fa391571   91fb91f3c3fe348b202db094fd624136a2ca7a1a5bc03b2f520d118ba79260964f67   95c2e9b0a2e1d54fb7792aafeca84701f7ff69cb202e4a3ad0c6d0a02651e6edd96fb   749551070f6a479c402165346dbaecba6fc30d23b5b88cb9fe   fd9344a99c5d265976e9ae760fb71e16f

我得到以下输出:

  

3b72efbfbdefbfbdefbfbd62efbfbdefbfbd2563efbfbd125563222c50efbfbdefbfbd   efbfbd505fefbfbddabaefbfbd4b657704efbfbd391571efbfbdefbfbdefbfbdefbfbd   efbfbd34efbfbd202defbfbdefbfbdefbfbd624136efbfbdefbfbd7a1a5befbfbd3b2f   520d11efbfbdefbfbdefbfbd60efbfbd4f67efbfbdefbfbde9b0a2efbfbdefbfbd4fef   bfbd792aefbfbdefbfbd4701efbfbdefbfbd69efbfbd202e4a3aefbfbdefbfbdd0a026   51efbfbdefbfbdefbfbd6fefbfbd49551070efbfbd79efbfbd02165346dbaecba6efbf   bd30efbfbd3b5befbfbdcb9fefbfbdefbfbd344aefbfbdefbfbdefbfbd65efbfbd6eef   bfbdefbfbd60efbfbd

2 个答案:

答案 0 :(得分:1)

我将解码后的Base64保留为byte[]并对其进行编码:

    String b64 = "O3Kmyftikp0lY/8SVWMiLFCn9sdQX7HauqdLZXcE+jkVcZH7kfPD/ jSLIC2wlP1iQTaiynoaW8A7L1INEYunkmCWT2eVwumwouHVT7d5Kq /sqEcB9/9pyyAuSjrQxtCgJlHm7dlvt0lVEHD2pHnEAhZTRtuuy6b 8MNI7W4jLn+/ZNEqZxdJll26a52D7ceFv";

    StringBuilder hexStringBuilder = new StringBuilder();
    for (byte b : Base64.decode(b64, Base64.DEFAULT)) {
        hexStringBuilder.append(String.format("%02x", b));
    }

    String hex = hexStringBuilder.toString()

答案 1 :(得分:0)

您应该将base64解码为字节数组(byte[]),然后将字节数组十六进制编码为字符串。