Java Code Examples for org.bitcoinj.core.Base58#encode()

The following examples show how to use org.bitcoinj.core.Base58#encode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EOSSign.java    From token-core-android with Apache License 2.0 7 votes vote down vote up
private static String serialEOSSignature(byte[] data) {
  byte[] toHash = ByteUtil.concat(data, "K1".getBytes());
  RIPEMD160Digest digest = new RIPEMD160Digest();
  digest.update(toHash, 0, toHash.length);
  byte[] out = new byte[20];
  digest.doFinal(out, 0);
  byte[] checksumBytes = Arrays.copyOfRange(out, 0, 4);
  data = ByteUtil.concat(data, checksumBytes);
  return "SIG_K1_" + Base58.encode(data);
}
 
Example 2
Source File: Utils.java    From evt4j with MIT License 7 votes vote down vote up
@NotNull
public static String base58Check(byte[] key, @Nullable String keyType) {
    byte[] check = key;

    if (keyType != null) {
        check = ArrayUtils.addAll(key, keyType.getBytes());
    }

    byte[] hash = ripemd160(check);
    byte[] concat = ArrayUtils.addAll(key, ArrayUtils.subarray(hash, 0, 4));
    return Base58.encode(concat);
}
 
Example 3
Source File: types.java    From AndroidWallet with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String toString() {
    RIPEMD160Digest dig = new RIPEMD160Digest();
    dig.update(key_data, 0, key_data.length);
    byte[] out = new byte[20];
    dig.doFinal(out, 0);

    byte[] byteKeyData = new byte[37];
    System.arraycopy(key_data, 0, byteKeyData, 0, key_data.length);
    System.arraycopy(out, 0, byteKeyData, key_data.length, byteKeyData.length - key_data.length);

    String strResult = GRAPHENE_ADDRESS_PREFIX;
    strResult += Base58.encode(byteKeyData);

    return strResult;
}
 
Example 4
Source File: types.java    From AndroidWallet with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String toString() {
    byte[] data = new byte[key_data.length + 1 + 4];
    data[0] = (byte) 0x80;
    System.arraycopy(key_data, 0, data, 1, key_data.length);

    SHA256Digest digest = new SHA256Digest();
    digest.update(data, 0, key_data.length + 1);
    byte[] out = new byte[32];
    digest.doFinal(out, 0);

    digest.update(out, 0, out.length);
    digest.doFinal(out, 0);

    System.arraycopy(out, 0, data, key_data.length + 1, 4);
    return Base58.encode(data);
}
 
Example 5
Source File: EOSWalletTest.java    From token-core-android with Apache License 2.0 6 votes vote down vote up
@Test
public void generatePrvPubKey() {

  byte[] prvWIF = Base58.decode(WIF);
  // have omitted the checksum verification
  prvWIF = Arrays.copyOfRange(prvWIF, 1, prvWIF.length - 4);

  // use the privateKey to calculate the compressed public key directly
  ECKey ecKey = ECKey.fromPrivate(new BigInteger(1, prvWIF));
  byte[] pubKeyData = ecKey.getPubKey();
  RIPEMD160Digest digest = new RIPEMD160Digest();
  digest.update(pubKeyData, 0, pubKeyData.length);
  byte[] out = new byte[20];
  digest.doFinal(out, 0);
  byte[] checksumBytes = Arrays.copyOfRange(out, 0, 4);

  pubKeyData = ByteUtil.concat(pubKeyData, checksumBytes);
  String eosPK = "EOS" + Base58.encode(pubKeyData);
  Assert.assertEquals(PUBLIC_KEY, eosPK);
}
 
Example 6
Source File: EOSFormatter.java    From eosio-java with MIT License 5 votes vote down vote up
/**
 * Base58 encodes a private key after calculating and appending the checksum.
 *
 * @param pemKey -  Private key as byte[] to encode
 * @param keyType - input key type
 * @return Base58 encoded private key as byte[]
 * @throws Base58ManipulationError it private key encoding fails.
 */
@NotNull
public static String encodePrivateKey(@NotNull byte[] pemKey,
        @NotNull AlgorithmEmployed keyType) throws Base58ManipulationError {
    byte[] checkSum;
    String base58Key = "";

    switch (keyType) {
        case SECP256R1:
            checkSum = extractCheckSumRIPEMD160(pemKey,
                    SECP256R1_AND_PRIME256V1_CHECKSUM_VALIDATION_SUFFIX.getBytes());
            break;
        case PRIME256V1:
            checkSum = extractCheckSumRIPEMD160(pemKey,
                    SECP256R1_AND_PRIME256V1_CHECKSUM_VALIDATION_SUFFIX.getBytes());
            break;
        case SECP256K1:
            pemKey = Bytes.concat(new byte[]{((Integer) EOS_SECP256K1_HEADER_BYTE).byteValue()},
                    pemKey);
            checkSum = extractCheckSumSha256x2(pemKey);
            break;
        default:
            throw new Base58ManipulationError(ErrorConstants.CHECKSUM_GENERATION_ERROR);

    }

    base58Key = Base58.encode(Bytes.concat(pemKey, checkSum));

    if (base58Key.isEmpty()) {
        throw new Base58ManipulationError(ErrorConstants.BASE58_ENCODING_ERROR);
    } else {
        return base58Key;
    }

}
 
Example 7
Source File: EOSKey.java    From token-core-android with Apache License 2.0 5 votes vote down vote up
public String getPublicKeyAsHex() {
  ECKey ecKey = ECKey.fromPrivate(bytes);
  byte[] pubKeyData = ecKey.getPubKey();
  RIPEMD160Digest digest = new RIPEMD160Digest();
  digest.update(pubKeyData, 0, pubKeyData.length);
  byte[] out = new byte[20];
  digest.doFinal(out, 0);
  byte[] checksumBytes = Arrays.copyOfRange(out, 0, 4);

  pubKeyData = ByteUtil.concat(pubKeyData, checksumBytes);
  return "EOS" + Base58.encode(pubKeyData);
}
 
Example 8
Source File: EOSFormatter.java    From eosio-java with MIT License 4 votes vote down vote up
/**
 * Encoding PEM public key to EOS format.
 *
 * @param pemKey -  PEM key as byte[] to encode
 * @param keyType - Algorithm type used to create key
 * @param isLegacy - If the developer prefers a legacy version of a secp256k1 key that uses an
 * "EOS" prefix.
 * @return - EOS format of public key
 * @throws Base58ManipulationError if public key encoding fails.
 */
@NotNull
public static String encodePublicKey(@NotNull byte[] pemKey, @NotNull AlgorithmEmployed keyType,
        boolean isLegacy)
        throws Base58ManipulationError {
    String base58Key = "";
    if (pemKey.length == 0) {
        throw new IllegalArgumentException(ErrorConstants.PUBLIC_KEY_IS_EMPTY);
    }

    try {
        byte[] checkSum;
        switch (keyType) {
            case SECP256K1:
                if (isLegacy) {
                    checkSum = extractCheckSumRIPEMD160(pemKey,
                            LEGACY_CHECKSUM_VALIDATION_SUFFIX.getBytes());
                } else {
                    checkSum = extractCheckSumRIPEMD160(pemKey,
                            SECP256K1_CHECKSUM_VALIDATION_SUFFIX.getBytes());
                }
                break;
            case SECP256R1:
                checkSum = extractCheckSumRIPEMD160(pemKey,
                        SECP256R1_AND_PRIME256V1_CHECKSUM_VALIDATION_SUFFIX.getBytes());
                break;
            default:
                throw new Base58ManipulationError(ErrorConstants.UNSUPPORTED_ALGORITHM);

        }

        base58Key = Base58.encode(Bytes.concat(pemKey, checkSum));

        if (base58Key.equals("")) {
            throw new Base58ManipulationError(ErrorConstants.BASE58_ENCODING_ERROR);
        }

    } catch (Exception ex) {
        throw new Base58ManipulationError(ErrorConstants.BASE58_ENCODING_ERROR, ex);
    }

    //Add prefix
    StringBuilder builder = new StringBuilder(base58Key);
    switch (keyType) {
        case SECP256K1:
            if (isLegacy) {
                builder.insert(0, PATTERN_STRING_EOS_PREFIX_EOS);
            } else {
                builder.insert(0, PATTERN_STRING_EOS_PREFIX_PUB_K1);
            }
            break;
        case SECP256R1:
            builder.insert(0, PATTERN_STRING_EOS_PREFIX_PUB_R1);
            break;
        default:
            break;
    }
    base58Key = builder.toString();

    return base58Key;
}
 
Example 9
Source File: Multihash.java    From token-core-android with Apache License 2.0 4 votes vote down vote up
public String toBase58() {
  return Base58.encode(toBytes());
}
 
Example 10
Source File: IdentityKeystore.java    From token-core-android with Apache License 2.0 4 votes vote down vote up
public IdentityKeystore(Metadata metadata, List<String> mnemonicCodes, String password) {
  MnemonicUtil.validateMnemonics(mnemonicCodes);

  DeterministicSeed seed = new DeterministicSeed(mnemonicCodes, null, "", 0L);

  DeterministicKey masterPrivateKey = HDKeyDerivation.createMasterPrivateKey(seed.getSeedBytes());
  byte[] masterKey = masterPrivateKey.getPrivKeyBytes();

  String salt = metadata.isMainNet() ? "Automatic Backup Key Mainnet" : "Automatic Backup Key Testnet";
  byte[] backupKey = Hash.hmacSHA256(masterKey, salt.getBytes(Charset.forName("ASCII")));
  byte[] authenticationKey = Hash.hmacSHA256(backupKey, "Authentication Key".getBytes(Charset.forName("UTF-8")));
  ECKey authKey = ECKey.fromPrivate(authenticationKey);

  NetworkParameters networkParameters = metadata.isMainNet() ? MainNetParams.get() : TestNet3Params.get();

  String aPubHashHex = NumericUtil.bytesToHex(authKey.getPubKeyHash());
  int networkHeader = networkParameters.getAddressHeader();
  int version = 2;
  // this magic hex will start with 'im' after base58check
  String magicHex = "0fdc0c";
  String fullIdentifier = String.format("%s%02x%02x%s", magicHex, (byte) networkHeader, (byte) version, aPubHashHex);
  byte[] fullIdentifierBytes = NumericUtil.hexToBytes(fullIdentifier);
  byte[] checksumBytes = Arrays.copyOfRange(Sha256Hash.hashTwice(fullIdentifierBytes), 0, 4);
  byte[] identifierWithChecksum = ByteUtil.concat(fullIdentifierBytes, checksumBytes);
  this.identifier = Base58.encode(identifierWithChecksum);

  byte[] encKeyFullBytes = Hash.hmacSHA256(backupKey, "Encryption Key".getBytes(Charset.forName("UTF-8")));
  this.encKey = NumericUtil.bytesToHex(encKeyFullBytes);

  ECKey ecKey = ECKey.fromPrivate(encKeyFullBytes, false);
  this.ipfsId = new Multihash(Multihash.Type.sha2_256, Hash.sha256(ecKey.getPubKey())).toBase58();
  Crypto crypto = Crypto.createPBKDF2CryptoWithKDFCached(password, masterPrivateKey.serializePrivB58(networkParameters).getBytes(Charset.forName("UTF-8")));

  this.encAuthKey = crypto.deriveEncPair(password, authenticationKey);
  this.encMnemonic = crypto.deriveEncPair(password, Joiner.on(" ").join(mnemonicCodes).getBytes());
  crypto.clearCachedDerivedKey();
  metadata.setTimestamp(DateUtil.getUTCTime());

  metadata.setSegWit(null);
  this.metadata = metadata;
  this.crypto = crypto;

  this.version = VERSION;
  this.walletIDs = new ArrayList<>();
}
 
Example 11
Source File: MultiChainAddressGenerator.java    From polling-station-app with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Converts a given public key to a valid MultiChain address.
 * See {@link <a href="http://www.multichain.com/developers/address-key-format/">MultiChain Documentation</a>}
 * @param pubKey byte array containing the public key
 * @return String representing the corresponding address.
 */
public static String getPublicAddress(String[] version, String addressChecksum, byte[] pubKey) {
    //Step 3
    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("SHA-256");
        digest.reset();
        byte[] hash = digest.digest(pubKey);

        //Step 4
        RIPEMD160Digest ripemd = new RIPEMD160Digest();
        ripemd.update(hash, 0, hash.length);
        byte[] out = new byte[20];
        ripemd.doFinal(out, 0);
        String hashStr = Util.byteArrayToHexString(out);

        //Step 5
        String step5 = "";
        if (BuildConfig.DEBUG && version.length != 4) throw new AssertionError("Version length != 4");
        for (int i = 0; i < 4; i++) { //Assumes version.length == 4
            step5 += version[i] + hashStr.substring((i*10),(i*10)+10);
        }
        digest.reset();

        //Step 6
        byte[] step6 = digest.digest(Util.hexStringToByteArray(step5));
        digest.reset();

        //Step 7
        byte[] step7 = digest.digest(step6);
        digest.reset();

        //Step 8
        byte[] checksum = new byte[]{ step7[0],step7[1],step7[2],step7[3] };

        //Step 9
        byte[] byteAddressChecksum = Util.hexStringToByteArray(addressChecksum);
        byte[] xor = new byte[4];
        for (int i = 0; i < 4; i++) {
            int xorvalue = (int)checksum[i] ^ (int)byteAddressChecksum[i];
            xor[i] = (byte)(0xff & xorvalue);
        }

        //Step 10
        String addressbytes = step5 + Util.byteArrayToHexString(xor);

        //Step 11
        String address = Base58.encode(Util.hexStringToByteArray(addressbytes));
        return address;
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
        return null;
    }
}