org.bitcoinj.core.Base58 Java Examples
The following examples show how to use
org.bitcoinj.core.Base58.
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: Utils.java From evt4j with MIT License | 7 votes |
@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 #2
Source File: EOSSign.java From token-core-android with Apache License 2.0 | 7 votes |
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 #3
Source File: types.java From AndroidWallet with GNU General Public License v3.0 | 6 votes |
@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 #4
Source File: ContractBuilder.java From guarda-android-wallets with GNU General Public License v3.0 | 6 votes |
private String convertParameter(ContractMethodParameter parameter) { String _value = parameter.getValue(); if (!parameterIsArray(parameter)) { if (parameter.getType().contains(TYPE_INT)) { return appendNumericPattern(convertToByteCode(new BigInteger(_value))); } else if (parameter.getType().contains(TYPE_STRING)) { return getStringOffset(parameter); } else if (parameter.getType().contains(TYPE_ADDRESS) && _value.length() == 34) { byte[] decode = Base58.decode(_value); String toHexString = Hex.toHexString(decode); String substring = toHexString.substring(2, 42); return appendAddressPattern(substring); } else if (parameter.getType().contains(TYPE_ADDRESS)) { return getStringOffset(parameter); } else if (parameter.getType().contains(TYPE_BOOL)) { return appendBoolean(_value); } } else { return getStringOffset(parameter); } return ""; }
Example #5
Source File: EOSWalletTest.java From token-core-android with Apache License 2.0 | 6 votes |
@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: types.java From AndroidWallet with GNU General Public License v3.0 | 6 votes |
public public_key_type(String strBase58) throws NoSuchAlgorithmException { String strPrefix = GRAPHENE_ADDRESS_PREFIX; byte[] byteKeyData = Base58.decode(strBase58.substring(strPrefix.length())); binary_key binaryKey = new binary_key(byteKeyData); RIPEMD160Digest digest = new RIPEMD160Digest(); digest.update(binaryKey.data, 0, binaryKey.data.length); byte[] out = new byte[20]; digest.doFinal(out, 0); byte[] byteOut = new byte[4]; System.arraycopy(out, 0, byteOut, 0, byteOut.length); int nByteOut = ByteBuffer.wrap(byteOut).getInt(); if (nByteOut != binaryKey.check) { throw new RuntimeException("Public key is not valid"); } key_data = binaryKey.data; }
Example #7
Source File: types.java From AndroidWallet with GNU General Public License v3.0 | 6 votes |
@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 #8
Source File: types.java From AndroidWallet with GNU General Public License v3.0 | 5 votes |
public private_key_type(String strBase58) throws KeyInvalideException, AddressFormatException { byte wif_bytes[] = Base58.decode(strBase58); if (wif_bytes.length < key_data.length) { throw new KeyInvalideException("Private key is not valid"); } System.arraycopy(wif_bytes, 1, key_data, 0, key_data.length); SHA256Digest digest = new SHA256Digest(); digest.update(wif_bytes, 0, wif_bytes.length - 4); byte[] hashCheck = new byte[32]; digest.doFinal(hashCheck, 0); byte[] hashCheck2 = new byte[32]; digest.update(hashCheck, 0, hashCheck.length); digest.doFinal(hashCheck2, 0); byte check[] = new byte[4]; System.arraycopy(wif_bytes, wif_bytes.length - check.length, check, 0, check.length); byte[] check1 = new byte[4]; byte[] check2 = new byte[4]; System.arraycopy(hashCheck, 0, check1, 0, check1.length); System.arraycopy(hashCheck2, 0, check2, 0, check2.length); if (!Arrays.equals(check1, check) && !Arrays.equals(check2, check)) { throw new KeyInvalideException("Private key is not valid"); } }
Example #9
Source File: ZenCash.java From bisq-assets with GNU Affero General Public License v3.0 | 5 votes |
@Override public AddressValidationResult validate(String address) { byte[] byteAddress; try { // Get the non Base58 form of the address and the bytecode of the first two bytes byteAddress = Base58.decodeChecked(address); } catch (AddressFormatException e) { // Unhandled Exception (probably a checksum error) return AddressValidationResult.invalidAddress(e); } int version0 = byteAddress[0] & 0xFF; int version1 = byteAddress[1] & 0xFF; // We only support public ("zn" (0x20,0x89), "t1" (0x1C,0xB8)) // and multisig ("zs" (0x20,0x96), "t3" (0x1C,0xBD)) addresses // Fail for private addresses if (version0 == 0x16 && version1 == 0x9A) // Address starts with "zc" return AddressValidationResult.invalidAddress("", "validation.altcoin.zAddressesNotSupported"); if (version0 == 0x1C && (version1 == 0xB8 || version1 == 0xBD)) // "t1" or "t3" address return AddressValidationResult.validAddress(); if (version0 == 0x20 && (version1 == 0x89 || version1 == 0x96)) // "zn" or "zs" address return AddressValidationResult.validAddress(); // Unknown Type return AddressValidationResult.invalidStructure(); }
Example #10
Source File: Utils.java From evt4j with MIT License | 5 votes |
public static byte[] base58CheckDecode(String key, @Nullable String keyType) throws Base58CheckException { byte[] decoded; try { // base58 decode decoded = Base58.decode(key); } catch (AddressFormatException ex) { throw new Base58CheckException(ex.getMessage(), ex); } // split the byte slice byte[] data = ArrayUtils.subarray(decoded, 0, decoded.length - 4); byte[] checksum = ArrayUtils.subarray(decoded, decoded.length - 4, decoded.length); if (keyType != null) { data = ArrayUtils.addAll(data, keyType.getBytes()); } // ripemd160 input, sign 4 bytes to compare byte[] hash = ripemd160(data); // if pass, return data, otherwise throw ex // compare two checksum boolean isEqual = true; for (int i = 0; i < checksum.length; i++) { if (hash[i] != checksum[i]) { isEqual = false; } } if (!isEqual) { throw new Base58CheckException(); } if (keyType != null) { return ArrayUtils.subarray(data, 0, data.length - keyType.getBytes().length); } return data; }
Example #11
Source File: EOSKey.java From token-core-android with Apache License 2.0 | 5 votes |
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 #12
Source File: Horizen.java From bisq with GNU Affero General Public License v3.0 | 5 votes |
@Override public AddressValidationResult validate(String address) { byte[] byteAddress; try { // Get the non Base58 form of the address and the bytecode of the first two bytes byteAddress = Base58.decodeChecked(address); } catch (AddressFormatException e) { // Unhandled Exception (probably a checksum error) return AddressValidationResult.invalidAddress(e); } int version0 = byteAddress[0] & 0xFF; int version1 = byteAddress[1] & 0xFF; // We only support public ("zn" (0x20,0x89), "t1" (0x1C,0xB8)) // and multisig ("zs" (0x20,0x96), "t3" (0x1C,0xBD)) addresses // Fail for private addresses if (version0 == 0x16 && version1 == 0x9A) // Address starts with "zc" return AddressValidationResult.invalidAddress("", "validation.altcoin.zAddressesNotSupported"); if (version0 == 0x1C && (version1 == 0xB8 || version1 == 0xBD)) // "t1" or "t3" address return AddressValidationResult.validAddress(); if (version0 == 0x20 && (version1 == 0x89 || version1 == 0x96)) // "zn" or "zs" address return AddressValidationResult.validAddress(); // Unknown Type return AddressValidationResult.invalidStructure(); }
Example #13
Source File: EOSFormatter.java From eosio-java with MIT License | 5 votes |
/** * 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 #14
Source File: Mile.java From bisq with GNU Affero General Public License v3.0 | 5 votes |
@Override public AddressValidationResult validate(String address) { byte[] decoded; try { decoded = Base58.decode(address); } catch (AddressFormatException e) { return AddressValidationResult.invalidAddress(e.getMessage()); } if (decoded.length != 32 + 4) return AddressValidationResult.invalidAddress("Invalid address"); byte[] data = Arrays.copyOfRange(decoded, 0, decoded.length - 4); byte[] addrChecksum = Arrays.copyOfRange(decoded, decoded.length - 4, decoded.length); Checksum checksum = new CRC32(); checksum.update(data, 0, data.length); long checksumValue = checksum.getValue(); if ((byte)(checksumValue & 0xff) != addrChecksum[0] || (byte)((checksumValue >> 8) & 0xff) != addrChecksum[1] || (byte)((checksumValue >> 16) & 0xff) != addrChecksum[2] || (byte)((checksumValue >> 24) & 0xff) != addrChecksum[3]) { return AddressValidationResult.invalidAddress("Invalid address checksum"); } return AddressValidationResult.validAddress(); }
Example #15
Source File: Ergo.java From bisq with GNU Affero General Public License v3.0 | 5 votes |
@Override public AddressValidationResult validate(String address) { try { byte[] decoded = Base58.decode(address); if (decoded.length < 4) { return AddressValidationResult.invalidAddress("Input too short: " + decoded.length); } if (decoded[0] != 1 && decoded[0] != 2 && decoded[0] != 3) { return AddressValidationResult.invalidAddress("Invalid prefix"); } } catch (AddressFormatException e) { return AddressValidationResult.invalidAddress(e); } return AddressValidationResult.validAddress(); }
Example #16
Source File: MultiChainAddressGenerator.java From polling-station-app with GNU Lesser General Public License v3.0 | 4 votes |
/** * 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; } }
Example #17
Source File: Util.java From zencash-swing-wallet-ui with MIT License | 4 votes |
public static String wifToHex(String wifKey) throws Exception { byte[] bytes = Base58.decode(wifKey); String pk = Util.encodeHexArray(bytes); pk = pk.substring(2, pk.length() - 10); return pk; }
Example #18
Source File: BIP32Test.java From GreenBits with GNU General Public License v3.0 | 4 votes |
private String testEncode(String what) { return HEX.encode(Base58.decodeChecked(what)); }
Example #19
Source File: Multihash.java From token-core-android with Apache License 2.0 | 4 votes |
public static Multihash fromBase58(String base58) { return new Multihash(Base58.decode(base58)); }
Example #20
Source File: BIP32Test.java From green_android with GNU General Public License v3.0 | 4 votes |
private String testEncode(String what) { return HEX.encode(Base58.decodeChecked(what)); }
Example #21
Source File: IdentityKeystore.java From token-core-android with Apache License 2.0 | 4 votes |
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 #22
Source File: EOSFormatter.java From eosio-java with MIT License | 4 votes |
/** * This method converts a signature to a EOS compliant form. The signature to be converted must * be an The ECDSA signature that is a DER encoded ASN.1 sequence of two integer fields (see * ECDSA-Sig-Value in rfc3279 section 2.2.3). * * The DER encoded ECDSA signature follows the following format: Byte 1 - Sequence (Should be * 30) Byte 2 - Signature length Byte 3 - R Marker (0x02) Byte 4 - R length Bytes 5 to 37 or 38- * R Byte After R - S Marker (0x02) Byte After S Marker - S Length Bytes After S Length - S * (always 32-33 bytes) Byte Final - Hash Type * * @param signatureDER ECDSA DER encoded signature as byte array * @param signableTransaction Transaction in signable format * @param publicKeyPEM public key in PEM format * @return EOS format of signature * @throws EOSFormatterError if DER conversion to EOS format fails. */ @NotNull public static String convertDERSignatureToEOSFormat(@NotNull byte[] signatureDER, @NotNull byte[] signableTransaction, @NotNull String publicKeyPEM) throws EOSFormatterError { String eosFormattedSignature = ""; try (ASN1InputStream asn1InputStream = new ASN1InputStream(signatureDER)) { PEMProcessor publicKey = new PEMProcessor(publicKeyPEM); AlgorithmEmployed algorithmEmployed = publicKey.getAlgorithm(); byte[] keyData = publicKey.getKeyData(); DLSequence sequence = (DLSequence) asn1InputStream.readObject(); BigInteger r = ((ASN1Integer) sequence.getObjectAt(0)).getPositiveValue(); BigInteger s = ((ASN1Integer) sequence.getObjectAt(1)).getPositiveValue(); s = checkAndHandleLowS(s, algorithmEmployed); /* Get recovery ID. This is the index of the public key (0-3) that represents the expected public key used to sign the transaction. */ int recoverId = getRecoveryId(r, s, Sha256Hash.of(signableTransaction), keyData, algorithmEmployed); if (recoverId < 0) { throw new IllegalStateException( ErrorConstants.COULD_NOT_RECOVER_PUBLIC_KEY_FROM_SIG); } //Add RecoveryID + 27 + 4 to create the header byte recoverId += VALUE_TO_ADD_TO_SIGNATURE_HEADER; byte headerByte = ((Integer) recoverId).byteValue(); byte[] decodedSignature = Bytes .concat(new byte[]{headerByte}, org.bitcoinj.core.Utils.bigIntegerToBytes(r,EXPECTED_R_OR_S_LENGTH), org.bitcoinj.core.Utils.bigIntegerToBytes(s,EXPECTED_R_OR_S_LENGTH)); if (algorithmEmployed.equals(AlgorithmEmployed.SECP256K1) && !isCanonical(decodedSignature)) { throw new IllegalArgumentException(ErrorConstants.NON_CANONICAL_SIGNATURE); } //Add checksum to signature byte[] signatureWithCheckSum; String signaturePrefix; switch (algorithmEmployed) { case SECP256R1: signatureWithCheckSum = addCheckSumToSignature(decodedSignature, SECP256R1_AND_PRIME256V1_CHECKSUM_VALIDATION_SUFFIX.getBytes()); signaturePrefix = PATTERN_STRING_EOS_PREFIX_SIG_R1; break; case SECP256K1: signatureWithCheckSum = addCheckSumToSignature(decodedSignature, SECP256K1_CHECKSUM_VALIDATION_SUFFIX.getBytes()); signaturePrefix = PATTERN_STRING_EOS_PREFIX_SIG_K1; break; default: throw new EOSFormatterError(ErrorConstants.UNSUPPORTED_ALGORITHM); } //Base58 encode signature and add pertinent EOS prefix eosFormattedSignature = signaturePrefix.concat(Base58.encode(signatureWithCheckSum)); } catch (Exception e) { throw new EOSFormatterError(ErrorConstants.SIGNATURE_FORMATTING_ERROR, e); } return eosFormattedSignature; }
Example #23
Source File: Multihash.java From token-core-android with Apache License 2.0 | 4 votes |
public String toBase58() { return Base58.encode(toBytes()); }
Example #24
Source File: BIP32Test.java From bcm-android with GNU General Public License v3.0 | 4 votes |
private String testEncode(String what) { return HEX.encode(Base58.decodeChecked(what)); }
Example #25
Source File: BIP38PrivateKeyTest.java From bcm-android with GNU General Public License v3.0 | 4 votes |
@Test(expected = AddressFormatException.InvalidDataLength.class) public void fromBase58_invalidLength() { String base58 = Base58.encodeChecked(1, new byte[16]); BIP38PrivateKey.fromBase58(null, base58); }
Example #26
Source File: EOSFormatter.java From eosio-java with MIT License | 4 votes |
/** * Base58 decodes a public key and validates checksum. * * @param strKey Base58 encoded public key in string format. * @param keyPrefix EOS specific key type prefix (i.e. PUB_R1_, PUB_K1_, or EOS). * @return Base58 decoded public key as byte[] * @throws Base58ManipulationError if public key decoding fails. */ @NotNull public static byte[] decodePublicKey(@NotNull String strKey, String keyPrefix) throws Base58ManipulationError { if (strKey.isEmpty()) { throw new IllegalArgumentException("Input key to decode can't be empty."); } byte[] decodedKey = null; try { byte[] base58Decoded = Base58.decode(strKey); byte[] firstCheckSum = Arrays .copyOfRange(base58Decoded, base58Decoded.length - CHECKSUM_BYTES, base58Decoded.length); decodedKey = Arrays .copyOfRange(base58Decoded, 0, base58Decoded.length - CHECKSUM_BYTES); switch (keyPrefix) { case PATTERN_STRING_EOS_PREFIX_PUB_R1: if (invalidRipeMD160CheckSum(decodedKey, firstCheckSum, SECP256R1_AND_PRIME256V1_CHECKSUM_VALIDATION_SUFFIX.getBytes())) { throw new IllegalArgumentException( ErrorConstants.BASE58_INVALID_CHECKSUM); } break; case PATTERN_STRING_EOS_PREFIX_PUB_K1: if (invalidRipeMD160CheckSum(decodedKey, firstCheckSum, SECP256K1_CHECKSUM_VALIDATION_SUFFIX.getBytes())) { throw new IllegalArgumentException( ErrorConstants.BASE58_INVALID_CHECKSUM); } break; case PATTERN_STRING_EOS_PREFIX_EOS: if (invalidRipeMD160CheckSum(decodedKey, firstCheckSum, LEGACY_CHECKSUM_VALIDATION_SUFFIX.getBytes())) { throw new IllegalArgumentException( ErrorConstants.BASE58_INVALID_CHECKSUM); } break; default: break; } } catch (Exception ex) { throw new Base58ManipulationError(ErrorConstants.BASE58_DECODING_ERROR, ex); } return decodedKey; }
Example #27
Source File: EOSFormatter.java From eosio-java with MIT License | 4 votes |
/** * 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 #28
Source File: EOSFormatter.java From eosio-java with MIT License | 4 votes |
/** * This method Base58 decodes the private key and validates its checksum. * * @param strKey Base58 value of the key * @param keyType key type * @return Base58 decoded key minus checksum * @throws Base58ManipulationError if private key decoding fails. */ @NotNull private static byte[] decodePrivateKey(@NotNull String strKey, AlgorithmEmployed keyType) throws Base58ManipulationError { if (strKey.isEmpty()) { throw new IllegalArgumentException(ErrorConstants.BASE58_EMPTY_KEY); } byte[] decodedKey; try { byte[] base58Decoded = Base58.decode(strKey); byte[] firstCheckSum = Arrays .copyOfRange(base58Decoded, base58Decoded.length - CHECKSUM_BYTES, base58Decoded.length); decodedKey = Arrays .copyOfRange(base58Decoded, 0, base58Decoded.length - CHECKSUM_BYTES); switch (keyType) { case SECP256R1: byte[] secp256r1Suffix = SECP256R1_AND_PRIME256V1_CHECKSUM_VALIDATION_SUFFIX .getBytes(); if (invalidRipeMD160CheckSum(decodedKey, firstCheckSum, secp256r1Suffix)) { throw new IllegalArgumentException(ErrorConstants.BASE58_INVALID_CHECKSUM); } break; case PRIME256V1: byte[] prime256v1Suffix = SECP256R1_AND_PRIME256V1_CHECKSUM_VALIDATION_SUFFIX .getBytes(); if (invalidRipeMD160CheckSum(decodedKey, firstCheckSum, prime256v1Suffix)) { throw new IllegalArgumentException(ErrorConstants.BASE58_INVALID_CHECKSUM); } break; case SECP256K1: if (invalidSha256x2CheckSum(decodedKey, firstCheckSum)) { throw new IllegalArgumentException(ErrorConstants.BASE58_INVALID_CHECKSUM); } break; default: throw new Base58ManipulationError(ErrorConstants.UNSUPPORTED_ALGORITHM); } // trim 0x80 out if the key size is more than 32 bytes // this code apply for key has more than 32 byte and non R1 key if (decodedKey.length > STANDARD_KEY_LENGTH && keyType != AlgorithmEmployed.SECP256R1) { // Slice out the first byte decodedKey = Arrays.copyOfRange(decodedKey, 1, decodedKey.length); if (decodedKey.length > STANDARD_KEY_LENGTH && decodedKey[STANDARD_KEY_LENGTH] == ((Integer) 1).byteValue()) { // Slice out last byte decodedKey = Arrays.copyOfRange(decodedKey, 0, decodedKey.length - 1); } } } catch (Exception ex) { throw new Base58ManipulationError(ErrorConstants.BASE58_DECODING_ERROR, ex); } return decodedKey; }
Example #29
Source File: EOSFormatter.java From eosio-java with MIT License | 4 votes |
/** * This method converts a signature to a EOS compliant form. The signature to be converted must * be an The ECDSA signature that is a DER encoded ASN.1 sequence of two integer fields (see * ECDSA-Sig-Value in rfc3279 section 2.2.3). This method should be used when only the R and S * values of the signature are available. * * The DER encoded ECDSA signature follows the following format: Byte 1 - Sequence (Should be * 30) Byte 2 - Signature length Byte 3 - R Marker (0x02) Byte 4 - R length Bytes 5 to 37 or 38- * R Byte After R - S Marker (0x02) Byte After S Marker - S Length Bytes After S Length - S * (always 32-33 bytes) Byte Final - Hash Type * * @param signatureR R value as BigInteger in string format * @param signatureS S value as BigInteger in string format * @param signableTransaction Transaction in signable format * @param publicKeyPEM Public Key used to sign in PEM format * @return EOS format of signature * @throws EOSFormatterError if conversion to EOS format fails. */ @NotNull public static String convertRawRandSofSignatureToEOSFormat(@NotNull String signatureR, String signatureS, @NotNull byte[] signableTransaction, @NotNull String publicKeyPEM) throws EOSFormatterError { String eosFormattedSignature = ""; try { PEMProcessor publicKey = new PEMProcessor(publicKeyPEM); AlgorithmEmployed algorithmEmployed = publicKey.getAlgorithm(); byte[] keyData = publicKey.getKeyData(); BigInteger r = new BigInteger(signatureR); BigInteger s = new BigInteger(signatureS); s = checkAndHandleLowS(s, algorithmEmployed); /* Get recovery ID. This is the index of the public key (0-3) that represents the expected public key used to sign the transaction. */ int recoverId = getRecoveryId(r, s, Sha256Hash.of(signableTransaction), keyData, algorithmEmployed); if (recoverId < 0) { throw new IllegalStateException( ErrorConstants.COULD_NOT_RECOVER_PUBLIC_KEY_FROM_SIG); } //Add RecoveryID + 27 + 4 to create the header byte recoverId += VALUE_TO_ADD_TO_SIGNATURE_HEADER; byte headerByte = ((Integer) recoverId).byteValue(); byte[] decodedSignature = Bytes .concat(new byte[]{headerByte}, org.bitcoinj.core.Utils.bigIntegerToBytes(r,EXPECTED_R_OR_S_LENGTH), org.bitcoinj.core.Utils.bigIntegerToBytes(s,EXPECTED_R_OR_S_LENGTH)); if (algorithmEmployed.equals(AlgorithmEmployed.SECP256K1) && !isCanonical(decodedSignature)) { throw new EosFormatterSignatureIsNotCanonicalError(ErrorConstants.NON_CANONICAL_SIGNATURE); } //Add checksum to signature byte[] signatureWithCheckSum; String signaturePrefix; switch (algorithmEmployed) { case SECP256R1: signatureWithCheckSum = addCheckSumToSignature(decodedSignature, SECP256R1_AND_PRIME256V1_CHECKSUM_VALIDATION_SUFFIX.getBytes()); signaturePrefix = PATTERN_STRING_EOS_PREFIX_SIG_R1; break; case SECP256K1: signatureWithCheckSum = addCheckSumToSignature(decodedSignature, SECP256K1_CHECKSUM_VALIDATION_SUFFIX.getBytes()); signaturePrefix = PATTERN_STRING_EOS_PREFIX_SIG_K1; break; default: throw new EOSFormatterError(ErrorConstants.UNSUPPORTED_ALGORITHM); } //Base58 encode signature and add pertinent EOS prefix eosFormattedSignature = signaturePrefix.concat(Base58.encode(signatureWithCheckSum)); } catch (Exception e) { throw new EOSFormatterError(ErrorConstants.SIGNATURE_FORMATTING_ERROR, e); } return eosFormattedSignature; }