com.google.common.io.BaseEncoding#decode ( )源码实例Demo

下面列出了com.google.common.io.BaseEncoding#decode ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: AndroidWallet   文件: ripe_md160_object.java

@Override
public ripe_md160_object deserialize(JsonElement json,
                                     Type typeOfT,
                                     JsonDeserializationContext context) throws JsonParseException {
    ripe_md160_object ripemd160Object = new ripe_md160_object();
    BaseEncoding encoding = BaseEncoding.base16().lowerCase();
    byte[] byteContent = encoding.decode(json.getAsString());
    if (byteContent.length != 20) {
        throw new JsonParseException("ripe_md160_object size not correct.");
    }
    for (int i = 0; i < 5; ++i) {
        ripemd160Object.hash[i] = ((byteContent[i * 4 + 3] & 0xff) << 24) |
                ((byteContent[i * 4 + 2] & 0xff) << 16) |
                ((byteContent[i * 4 + 1] & 0xff) << 8) |
                ((byteContent[i * 4 ] & 0xff));
    }

    return ripemd160Object;
}
 

@Override
public ripemd160_object deserialize(JsonElement json,
                                    Type typeOfT,
                                    JsonDeserializationContext context) throws JsonParseException {
    ripemd160_object ripemd160Object = new ripemd160_object();
    BaseEncoding encoding = BaseEncoding.base16().lowerCase();
    byte[] byteContent = encoding.decode(json.getAsString());
    if (byteContent.length != 20) {
        throw new JsonParseException("ripemd160_object size not correct.");
    }
    for (int i = 0; i < 5; ++i) {
        ripemd160Object.hash[i] = ((byteContent[i * 4 + 3] & 0xff) << 24) |
                ((byteContent[i * 4 + 2] & 0xff) << 16) |
                ((byteContent[i * 4 + 1] & 0xff) << 8) |
                ((byteContent[i * 4 ] & 0xff));
    }

    return ripemd160Object;
}
 

@Override
public ripemd160_object deserialize(JsonElement json,
                                    Type typeOfT,
                                    JsonDeserializationContext context) throws JsonParseException {
    ripemd160_object ripemd160Object = new ripemd160_object();
    BaseEncoding encoding = BaseEncoding.base16().lowerCase();
    byte[] byteContent = encoding.decode(json.getAsString());
    if (byteContent.length != 20) {
        throw new JsonParseException("ripemd160_object size not correct.");
    }
    for (int i = 0; i < 5; ++i) {
        ripemd160Object.hash[i] = ((byteContent[i * 4 + 3] & 0xff) << 24) |
                ((byteContent[i * 4 + 2] & 0xff) << 16) |
                ((byteContent[i * 4 + 1] & 0xff) << 8) |
                ((byteContent[i * 4 ] & 0xff));
    }

    return ripemd160Object;
}
 

@Override
public SfsRequest call(SfsRequest httpServerRequest) {
    MultiMap params = httpServerRequest.params();

    String value = params.get(paramName);
    if (value != null) {
        boolean failed = false;
        BaseEncoding baseEncoding = base64();
        try {
            byte[] decoded = baseEncoding.decode(value);
            if (decoded == null || value.equals(baseEncoding.encode(decoded))) {
                failed = true;
            }
        } catch (Throwable e) {
            // do nothing
        }
        if (failed) {
            JsonObject jsonObject = new JsonObject()
                    .put("message", format("%s must be Base64 encoded", paramName));

            throw new HttpRequestValidationException(HTTP_BAD_REQUEST, jsonObject);
        }
    }
    return httpServerRequest;
}
 

/**
 * Decoding "TransactionResult" from "resultXdr".
 * This will be <code>Optional.absent()</code> if transaction has failed.
 */
public Optional<TransactionResult> getDecodedTransactionResult() throws IOException {
    if(!this.isSuccess()) {
        return Optional.absent();
    }

    if (this.transactionResult == null) {
        Optional<String> resultXDR = this.getResultXdr();
        if (!resultXDR.isPresent()) {
            return Optional.absent();
        }
        BaseEncoding base64Encoding = BaseEncoding.base64();
        byte[] bytes = base64Encoding.decode(resultXDR.get());
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        XdrDataInputStream xdrInputStream = new XdrDataInputStream(inputStream);
        this.transactionResult = TransactionResult.decode(xdrInputStream);
    }

    return Optional.of(this.transactionResult);
}
 
源代码6 项目: AndroidWallet   文件: sha256_object.java

@Override
public sha256_object deserialize(JsonElement json,
                                 Type typeOfT,
                                 JsonDeserializationContext context) throws JsonParseException {
    sha256_object sha256ObjectObject = new sha256_object();
    BaseEncoding encoding = BaseEncoding.base16().lowerCase();
    byte[] byteContent = encoding.decode(json.getAsString());
    if (byteContent.length != 32) {
        throw new JsonParseException("sha256_object size not correct.");
    }
    System.arraycopy(byteContent, 0, sha256ObjectObject.hash, 0, sha256ObjectObject.hash.length);
    sha256ObjectObject.hash = byteContent;
    return sha256ObjectObject;
}
 

@Override
public ByteBuffer deserialize(JsonElement json,
                              Type typeOfT,
                              JsonDeserializationContext context) throws JsonParseException {
    BaseEncoding encoding = BaseEncoding.base16().lowerCase();
    byte[] byteResult = encoding.decode(json.getAsString());
    ByteBuffer byteBuffer = ByteBuffer.wrap(byteResult);

    return byteBuffer;
}
 

@Override
public sha256_object deserialize(JsonElement json,
                                    Type typeOfT,
                                    JsonDeserializationContext context) throws JsonParseException {
    sha256_object sha256ObjectObject = new sha256_object();
    BaseEncoding encoding = BaseEncoding.base16().lowerCase();
    byte[] byteContent = encoding.decode(json.getAsString());
    if (byteContent.length != 32) {
        throw new JsonParseException("sha256_object size not correct.");
    }
    System.arraycopy(byteContent, 0, sha256ObjectObject.hash, 0, sha256ObjectObject.hash.length);
    sha256ObjectObject.hash = byteContent;
    return sha256ObjectObject;
}
 

@Override
public ByteBuffer deserialize(JsonElement json,
                              Type typeOfT,
                              JsonDeserializationContext context) throws JsonParseException {
    BaseEncoding encoding = BaseEncoding.base16().lowerCase();
    byte[] byteResult = encoding.decode(json.getAsString());
    ByteBuffer byteBuffer = ByteBuffer.wrap(byteResult);

    return byteBuffer;
}
 
源代码10 项目: bitshares_wallet   文件: sha256_object.java

@Override
public sha256_object deserialize(JsonElement json,
                                    Type typeOfT,
                                    JsonDeserializationContext context) throws JsonParseException {
    sha256_object sha256ObjectObject = new sha256_object();
    BaseEncoding encoding = BaseEncoding.base16().lowerCase();
    byte[] byteContent = encoding.decode(json.getAsString());
    if (byteContent.length != 32) {
        throw new JsonParseException("sha256_object size not correct.");
    }
    System.arraycopy(byteContent, 0, sha256ObjectObject.hash, 0, sha256ObjectObject.hash.length);
    sha256ObjectObject.hash = byteContent;
    return sha256ObjectObject;
}
 
源代码11 项目: java-stellar-sdk   文件: OperationTest.java

@Test
public void testManageSellOfferOperation_BadArithmeticRegression() throws IOException {
    // from https://github.com/stellar/java-stellar-sdk/issues/183

    String transactionEnvelopeToDecode = "AAAAAButy5zasS3DLZ5uFpZHL25aiHUfKRwdv1+3Wp12Ce7XAAAAZAEyGwYAAAAOAAAAAAAAAAAAAAABAAAAAQAAAAAbrcuc2rEtwy2ebhaWRy9uWoh1HykcHb9ft1qddgnu1wAAAAMAAAAAAAAAAUtJTgAAAAAARkrT28ebM6YQyhVZi1ttlwq/dk6ijTpyTNuHIMgUp+EAAAAAAAARPSfDKZ0AAv7oAAAAAAAAAAAAAAAAAAAAAXYJ7tcAAABAbE8rEoFt0Hcv41iwVCl74C1Hyr+Lj8ZyaYn7zTJhezClbc+pTW1KgYFIZOJiGVth2xFnBT1pMXuQkVdTlB3FCw==";
    BaseEncoding base64Encoding = BaseEncoding.base64();
    byte[] bytes = base64Encoding.decode(transactionEnvelopeToDecode);

    org.stellar.sdk.xdr.TransactionEnvelope transactionEnvelope = org.stellar.sdk.xdr.TransactionEnvelope.decode(new XdrDataInputStream(new ByteArrayInputStream(bytes)));
    assertEquals(1, transactionEnvelope.getV0().getTx().getOperations().length);

    ManageSellOfferOperation op = (ManageSellOfferOperation) Operation.fromXdr(transactionEnvelope.getV0().getTx().getOperations()[0]);

    assertEquals("3397.893306099996", op.getPrice());
}
 

@Test
public void testTransactionEnvelopeWithMemo() throws IOException {
    String transactionEnvelopeToDecode = "AAAAACq1Ixcw1fchtF5aLTSw1zaYAYjb3WbBRd4jqYJKThB9AAAAZAA8tDoAAAALAAAAAAAAAAEAAAAZR29sZCBwYXltZW50IGZvciBzZXJ2aWNlcwAAAAAAAAEAAAAAAAAAAQAAAAARREGslec48mbJJygIwZoLvRtL6/gGL4ss2TOpnOUOhgAAAAFHT0xEAAAAACq1Ixcw1fchtF5aLTSw1zaYAYjb3WbBRd4jqYJKThB9AAAAADuaygAAAAAAAAAAAA==";
    BaseEncoding base64Encoding = BaseEncoding.base64();
    byte[] bytes = base64Encoding.decode(transactionEnvelopeToDecode);

    TransactionEnvelope transactionEnvelope = TransactionEnvelope.decode(new XdrDataInputStream(new ByteArrayInputStream(bytes)));
    assertEquals(1, transactionEnvelope.getV0().getTx().getOperations().length);
    assertTrue(Arrays.equals(new byte[]{'G', 'O', 'L', 'D'}, transactionEnvelope.getV0().getTx().getOperations()[0].getBody().getPaymentOp().getAsset().getAlphaNum4().getAssetCode().getAssetCode4()));
}
 

@Override
public SfsRequest call(SfsRequest httpServerRequest) {
    MultiMap headers = httpServerRequest.headers();

    String value = headers.get(headerName);
    if (value != null) {
        boolean failed = false;
        BaseEncoding baseEncoding = base16().lowerCase();
        try {
            byte[] decoded = baseEncoding.decode(value);
            if (decoded == null) {
                failed = true;
            } else {
                String encoded = baseEncoding.encode(decoded);
                if (!value.equals(encoded)) {
                    failed = true;
                }
            }
        } catch (Throwable e) {
            // do nothing
        }
        if (failed) {
            JsonObject jsonObject = new JsonObject()
                    .put("message", format("%s must be Base16 lowercase encoded", headerName));

            throw new HttpRequestValidationException(HTTP_BAD_REQUEST, jsonObject);
        }
    }
    return httpServerRequest;
}
 
源代码14 项目: java-stellar-sdk   文件: OperationTest.java

@Test
public void testManageBuyOfferOperation_BadArithmeticRegression() throws IOException {
    // from https://github.com/stellar/java-stellar-sdk/issues/183

    String transactionEnvelopeToDecode = "AAAAAButy5zasS3DLZ5uFpZHL25aiHUfKRwdv1+3Wp12Ce7XAAAAZAEyGwYAAAAxAAAAAAAAAAAAAAABAAAAAQAAAAAbrcuc2rEtwy2ebhaWRy9uWoh1HykcHb9ft1qddgnu1wAAAAwAAAABS0lOAAAAAABGStPbx5szphDKFVmLW22XCr92TqKNOnJM24cgyBSn4QAAAAAAAAAAACNyOCfDKZ0AAv7oAAAAAAABv1IAAAAAAAAAAA==";
    BaseEncoding base64Encoding = BaseEncoding.base64();
    byte[] bytes = base64Encoding.decode(transactionEnvelopeToDecode);

    org.stellar.sdk.xdr.TransactionEnvelope transactionEnvelope = org.stellar.sdk.xdr.TransactionEnvelope.decode(new XdrDataInputStream(new ByteArrayInputStream(bytes)));
    assertEquals(1, transactionEnvelope.getV0().getTx().getOperations().length);

    ManageBuyOfferOperation op = (ManageBuyOfferOperation) Operation.fromXdr(transactionEnvelope.getV0().getTx().getOperations()[0]);

    assertEquals("3397.893306099996", op.getPrice());
}
 

/**
 * Creates a <code>Transaction</code> instance from previously build <code>TransactionEnvelope</code>
 * @param envelope Base-64 encoded <code>TransactionEnvelope</code>
 * @return
 * @throws IOException
 */
public static AbstractTransaction fromEnvelopeXdr(String envelope, Network network) throws IOException {
  BaseEncoding base64Encoding = BaseEncoding.base64();
  byte[] bytes = base64Encoding.decode(envelope);

  TransactionEnvelope transactionEnvelope = TransactionEnvelope.decode(new XdrDataInputStream(new ByteArrayInputStream(bytes)));
  return fromEnvelopeXdr(transactionEnvelope, network);
}
 

@Test
public void testRoundtrip() throws IOException {
    String txBody = "AAAAAM6jLgjKjuXxWkir4M7v0NqoOfODXcFnn6AGlP+d4RxAAAAAZAAIiE4AAAABAAAAAAAAAAEAAAAcyKMl+WDSzuttWkF2DvzKAkkEqeSZ4cZihjGJEAAAAAEAAAAAAAAAAQAAAAAgECmBaDwiRPE1z2vAE36J+45toU/ZxdvpR38tc0HvmgAAAAAAAAAAAJiWgAAAAAAAAAABneEcQAAAAECeXDKebJoAbST1T2AbDBui9K0TbSM8sfbhXUAZ2ROAoCRs5cG1pRvY+ityyPWFEKPd7+3qEupavkAZ/+L7/28G";
    BaseEncoding base64Encoding = BaseEncoding.base64();
    byte[] bytes = base64Encoding.decode(txBody);

    TransactionEnvelope transactionEnvelope = TransactionEnvelope.decode(new XdrDataInputStream(new ByteArrayInputStream(bytes)));
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();

    transactionEnvelope.encode(new XdrDataOutputStream(byteOutputStream));
    String serialized = base64Encoding.encode(byteOutputStream.toByteArray());
    assertEquals(serialized, txBody);
}
 

@Test
public void testDecodeTxResult() throws IOException {
    // pubnet - ledgerseq 5845058, txid  d5ec6645d86cdcae8212cbe60feaefb8d6b1a8b7d11aeea590608b0863ace4de

    String txResult = "1exmRdhs3K6CEsvmD+rvuNaxqLfRGu6lkGCLCGOs5N4AAAAAAAAAZAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAA==";
    BaseEncoding base64Encoding = BaseEncoding.base64();
    byte[] bytes = base64Encoding.decode(txResult);

    TransactionResultPair transactionResult = TransactionResultPair.decode(new XdrDataInputStream(new ByteArrayInputStream(bytes)));
    assertEquals(TransactionResultCode.txSUCCESS, transactionResult.getResult().getResult().getDiscriminant());
}
 

@Test
public void testDecodeTxMeta() throws IOException {
    // pubnet - ledgerseq 5845058, txid  d5ec6645d86cdcae8212cbe60feaefb8d6b1a8b7d11aeea590608b0863ace4de

    String txMeta = "AAAAAAAAAAEAAAADAAAAAABZMEIAAAAAAAAAAN1WENUWtSJL+M+tGluVdjhsBb27iFtEjYeHD7YBOwWlAAAAAC09a8AAWTBCAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAwBZL8QAAAAAAAAAAP1qe44j+i4uIT+arbD4QDQBt8ryEeJd7a0jskQ3nwDeAALU1gZ4V7UACD1BAAAAHgAAAAoAAAAAAAAAAAAAAAABAAAAAAAACgAAAAARC07BokpLTOF+/vVKBwiAlop7hHGJTNeGGlY4MoPykwAAAAEAAAAAK+Lzfd3yDD+Ov0GbYu1g7SaIBrKZeBUxoCunkLuI7aoAAAABAAAAAERmsKL73CyLV/HvjyQCERDXXpWE70Xhyb6MR5qPO3yQAAAAAQAAAABSORGwAdyuanN3sNOHqNSpACyYdkUM3L8VafUu69EvEgAAAAEAAAAAeCzqJNkMM/jLvyuMIfyFHljBlLCtDyj17RMycPuNtRMAAAABAAAAAIEi4R7juq15ymL00DNlAddunyFT4FyUD4muC4t3bobdAAAAAQAAAACaNpLL5YMfjOTdXVEqrAh99LM12sN6He6pHgCRAa1f1QAAAAEAAAAAqB+lfAPV9ak+Zkv4aTNZwGaFFAfui4+yhM3dGhoYJ+sAAAABAAAAAMNJrEvdMg6M+M+n4BDIdzsVSj/ZI9SvAp7mOOsvAD/WAAAAAQAAAADbHA6xiKB1+G79mVqpsHMOleOqKa5mxDpP5KEp/Xdz9wAAAAEAAAAAAAAAAAAAAAEAWTBCAAAAAAAAAAD9anuOI/ouLiE/mq2w+EA0AbfK8hHiXe2tI7JEN58A3gAC1NXZOuv1AAg9QQAAAB4AAAAKAAAAAAAAAAAAAAAAAQAAAAAAAAoAAAAAEQtOwaJKS0zhfv71SgcIgJaKe4RxiUzXhhpWODKD8pMAAAABAAAAACvi833d8gw/jr9Bm2LtYO0miAaymXgVMaArp5C7iO2qAAAAAQAAAABEZrCi+9wsi1fx748kAhEQ116VhO9F4cm+jEeajzt8kAAAAAEAAAAAUjkRsAHcrmpzd7DTh6jUqQAsmHZFDNy/FWn1LuvRLxIAAAABAAAAAHgs6iTZDDP4y78rjCH8hR5YwZSwrQ8o9e0TMnD7jbUTAAAAAQAAAACBIuEe47qtecpi9NAzZQHXbp8hU+BclA+JrguLd26G3QAAAAEAAAAAmjaSy+WDH4zk3V1RKqwIffSzNdrDeh3uqR4AkQGtX9UAAAABAAAAAKgfpXwD1fWpPmZL+GkzWcBmhRQH7ouPsoTN3RoaGCfrAAAAAQAAAADDSaxL3TIOjPjPp+AQyHc7FUo/2SPUrwKe5jjrLwA/1gAAAAEAAAAA2xwOsYigdfhu/ZlaqbBzDpXjqimuZsQ6T+ShKf13c/cAAAABAAAAAAAAAAA=";
    BaseEncoding base64Encoding = BaseEncoding.base64();
    byte[] bytes = base64Encoding.decode(txMeta);

    TransactionMeta transactionMeta = TransactionMeta.decode(new XdrDataInputStream(new ByteArrayInputStream(bytes)));
    assertEquals(1, transactionMeta.getOperations().length);
}
 
源代码19 项目: java-stellar-sdk   文件: Sep10Challenge.java

/**
 * Reads a SEP 10 challenge transaction and returns the decoded transaction envelope and client account ID contained within.
 * <p>
 * It also verifies that transaction is signed by the server.
 * <p>
 * It does not verify that the transaction has been signed by the client or
 * that any signatures other than the servers on the transaction are valid. Use
 * one of the following functions to completely verify the transaction:
 * {@link Sep10Challenge#verifyChallengeTransactionSigners(String, String, Network, Set)} or
 * {@link Sep10Challenge#verifyChallengeTransactionThreshold(String, String, Network, int, Set)}
 *
 * @param challengeXdr    SEP-0010 transaction challenge transaction in base64.
 * @param serverAccountId Account ID for server's account.
 * @param network         The network to connect to for verifying and retrieving.
 * @return {@link ChallengeTransaction}, the decoded transaction envelope and client account ID contained within.
 * @throws InvalidSep10ChallengeException If the SEP-0010 validation fails, the exception will be thrown.
 * @throws IOException                    If read XDR string fails, the exception will be thrown.
 */
public static ChallengeTransaction readChallengeTransaction(String challengeXdr, String serverAccountId, Network network) throws InvalidSep10ChallengeException, IOException {
  // decode the received input as a base64-urlencoded XDR representation of Stellar transaction envelope
  AbstractTransaction parsed = Transaction.fromEnvelopeXdr(challengeXdr, network);
  if (!(parsed instanceof Transaction)) {
    throw new InvalidSep10ChallengeException("Transaction cannot be a fee bump transaction");
  }
  Transaction transaction = (Transaction)parsed;

  if (StrKey.decodeVersionByte(serverAccountId) != StrKey.VersionByte.ACCOUNT_ID) {
    throw new InvalidSep10ChallengeException("serverAccountId: "+serverAccountId+" is not a valid account id");
  }

  // verify that transaction source account is equal to the server's signing key
  if (!serverAccountId.equals(transaction.getSourceAccount())) {
    throw new InvalidSep10ChallengeException("Transaction source account is not equal to server's account.");
  }

  // verify that transaction sequenceNumber is equal to zero
  if (transaction.getSequenceNumber() != 0L) {
    throw new InvalidSep10ChallengeException("The transaction sequence number should be zero.");
  }

  // verify that transaction has time bounds set, and that current time is between the minimum and maximum bounds.
  if (transaction.getTimeBounds() == null) {
    throw new InvalidSep10ChallengeException("Transaction requires timebounds.");
  }

  long maxTime = transaction.getTimeBounds().getMaxTime();
  long minTime = transaction.getTimeBounds().getMinTime();
  if (maxTime == 0L) {
    throw new InvalidSep10ChallengeException("Transaction requires non-infinite timebounds.");
  }

  long currentTime = System.currentTimeMillis() / 1000L;
  if (currentTime < minTime || currentTime > maxTime) {
    throw new InvalidSep10ChallengeException("Transaction is not within range of the specified timebounds.");
  }

  // verify that transaction contains a single Manage Data operation and its source account is not null
  if (transaction.getOperations().length != 1) {
    throw new InvalidSep10ChallengeException("Transaction requires a single ManageData operation.");
  }
  Operation operation = transaction.getOperations()[0];
  if (!(operation instanceof ManageDataOperation)) {
    throw new InvalidSep10ChallengeException("Operation type should be ManageData.");
  }
  ManageDataOperation manageDataOperation = (ManageDataOperation) operation;

  // verify that transaction envelope has a correct signature by server's signing key
  String clientAccountId = manageDataOperation.getSourceAccount();
  if (clientAccountId == null) {
    throw new InvalidSep10ChallengeException("Operation should have a source account.");
  }

  if (StrKey.decodeVersionByte(clientAccountId) != StrKey.VersionByte.ACCOUNT_ID) {
    throw new InvalidSep10ChallengeException("clientAccountId: "+clientAccountId+" is not a valid account id");
  }

  // verify manage data value
  if (manageDataOperation.getValue().length != 64) {
    throw new InvalidSep10ChallengeException("Random nonce encoded as base64 should be 64 bytes long.");
  }

  BaseEncoding base64Encoding = BaseEncoding.base64();
  byte[] nonce;
  try {
    nonce = base64Encoding.decode(new String(manageDataOperation.getValue()));
  } catch (IllegalArgumentException e) {
    throw new InvalidSep10ChallengeException("Failed to decode random nonce provided in ManageData operation.", e);
  }

  if (nonce.length != 48) {
    throw new InvalidSep10ChallengeException("Random nonce before encoding as base64 should be 48 bytes long.");
  }

  if (!verifyTransactionSignature(transaction, serverAccountId)) {
    throw new InvalidSep10ChallengeException(String.format("Transaction not signed by server: %s.", serverAccountId));
  }

  return new ChallengeTransaction(transaction, clientAccountId);
}
 
源代码20 项目: java-stellar-sdk   文件: AccountResponse.java

/**
 * Gets raw value for a given key.
 * @param key Data entry name
 * @return raw value
 */
public byte[] getDecoded(String key) {
  BaseEncoding base64Encoding = BaseEncoding.base64();
  return base64Encoding.decode(this.get(key));
}