List of usage examples for org.bouncycastle.crypto.digests SHA256Digest doFinal
public int doFinal(byte[] out, int outOff)
From source file:TxOutput.java
License:Open Source License
public String getAddress() { // P2PKH Address if (script[0] == 0x76) { byte[] hash160 = Arrays.copyOfRange(script, 3, 23); return Utils.base58Encode((byte) 0x00, hash160); }//from w w w . j ava 2s . c o m // P2SH Address else if (Utils.getUnsignedByte(script[0]) == 0xa9) { byte[] hash160 = Arrays.copyOfRange(script, 2, 22); return Utils.base58Encode((byte) 0x05, hash160); } // P2PK Address Uncompressed else if (Utils.getUnsignedByte(script[0]) == 0x41 && Utils.getUnsignedByte(script[1]) == 0x04 && Utils.getUnsignedByte(script[script.length - 1]) == 0xac) { byte[] pk = Arrays.copyOfRange(script, 1, 66); SHA256Digest sha256 = new SHA256Digest(); sha256.update(pk, 0, pk.length); byte[] sha256out = new byte[32]; sha256.doFinal(sha256out, 0); RIPEMD160Digest ripemd160 = new RIPEMD160Digest(); ripemd160.update(sha256out, 0, sha256out.length); byte[] ripemd160out = new byte[20]; ripemd160.doFinal(ripemd160out, 0); return Utils.base58Encode((byte) 0x00, ripemd160out); } // P2PK Address Compressed else if ((Utils.getUnsignedByte(script[1]) == 0x03 || Utils.getUnsignedByte(script[1]) == 0x02) && Utils.getUnsignedByte(script[0]) == 21 && Utils.getUnsignedByte(script[script.length - 1]) == 0xac) { byte[] pk = Arrays.copyOfRange(script, 1, 34); SHA256Digest sha256 = new SHA256Digest(); sha256.update(pk, 0, pk.length); byte[] sha256out = new byte[32]; sha256.doFinal(sha256out, 0); RIPEMD160Digest ripemd160 = new RIPEMD160Digest(); ripemd160.update(sha256out, 0, sha256out.length); byte[] ripemd160out = new byte[20]; ripemd160.doFinal(ripemd160out, 0); return Utils.base58Encode((byte) 0x00, ripemd160out); } // Nonstandard else { return "Non Standard Output"; } }
From source file:co.rsk.validators.ProofOfWorkRule.java
License:Open Source License
@Override public boolean isValid(BlockHeader header) { // TODO: refactor this an move it to another class. Change the Global ProofOfWorkRule to AuthenticationRule. // TODO: Make ProofOfWorkRule one of the classes that inherits from AuthenticationRule. if (isFallbackMiningPossibleAndBlockSigned(header)) { boolean isValidFallbackSignature = validFallbackBlockSignature(constants, header, header.getBitcoinMergedMiningHeader()); if (!isValidFallbackSignature) { logger.warn("Fallback signature failed. Header {}", header.getShortHash()); }//www . j a va2 s . c o m return isValidFallbackSignature; } co.rsk.bitcoinj.core.NetworkParameters bitcoinNetworkParameters = bridgeConstants.getBtcParams(); MerkleProofValidator mpValidator; try { if (blockchainConfig.getConfigForBlock(header.getNumber()).isRskip92()) { mpValidator = new Rskip92MerkleProofValidator(header.getBitcoinMergedMiningMerkleProof()); } else { mpValidator = new GenesisMerkleProofValidator(bitcoinNetworkParameters, header.getBitcoinMergedMiningMerkleProof()); } } catch (RuntimeException ex) { logger.warn("Merkle proof can't be validated. Header {}", header.getShortHash(), ex); return false; } byte[] bitcoinMergedMiningCoinbaseTransactionCompressed = header .getBitcoinMergedMiningCoinbaseTransaction(); if (bitcoinMergedMiningCoinbaseTransactionCompressed == null) { logger.warn("Compressed coinbase transaction does not exist. Header {}", header.getShortHash()); return false; } if (header.getBitcoinMergedMiningHeader() == null) { logger.warn("Bitcoin merged mining header does not exist. Header {}", header.getShortHash()); return false; } BtcBlock bitcoinMergedMiningBlock = bitcoinNetworkParameters.getDefaultSerializer() .makeBlock(header.getBitcoinMergedMiningHeader()); BigInteger target = DifficultyUtils.difficultyToTarget(header.getDifficulty()); BigInteger bitcoinMergedMiningBlockHashBI = bitcoinMergedMiningBlock.getHash().toBigInteger(); if (bitcoinMergedMiningBlockHashBI.compareTo(target) > 0) { logger.warn("Hash {} is higher than target {}", bitcoinMergedMiningBlockHashBI.toString(16), target.toString(16)); return false; } byte[] bitcoinMergedMiningCoinbaseTransactionMidstate = new byte[RskMiningConstants.MIDSTATE_SIZE]; System.arraycopy(bitcoinMergedMiningCoinbaseTransactionCompressed, 0, bitcoinMergedMiningCoinbaseTransactionMidstate, 8, RskMiningConstants.MIDSTATE_SIZE_TRIMMED); byte[] bitcoinMergedMiningCoinbaseTransactionTail = new byte[bitcoinMergedMiningCoinbaseTransactionCompressed.length - RskMiningConstants.MIDSTATE_SIZE_TRIMMED]; System.arraycopy(bitcoinMergedMiningCoinbaseTransactionCompressed, RskMiningConstants.MIDSTATE_SIZE_TRIMMED, bitcoinMergedMiningCoinbaseTransactionTail, 0, bitcoinMergedMiningCoinbaseTransactionTail.length); byte[] expectedCoinbaseMessageBytes = org.bouncycastle.util.Arrays.concatenate(RskMiningConstants.RSK_TAG, header.getHashForMergedMining()); List<Byte> bitcoinMergedMiningCoinbaseTransactionTailAsList = Arrays .asList(ArrayUtils.toObject(bitcoinMergedMiningCoinbaseTransactionTail)); List<Byte> expectedCoinbaseMessageBytesAsList = Arrays .asList(ArrayUtils.toObject(expectedCoinbaseMessageBytes)); int rskTagPosition = Collections.lastIndexOfSubList(bitcoinMergedMiningCoinbaseTransactionTailAsList, expectedCoinbaseMessageBytesAsList); if (rskTagPosition == -1) { logger.warn( "bitcoin coinbase transaction tail message does not contain expected RSKBLOCK:RskBlockHeaderHash. Expected: {} . Actual: {} .", Arrays.toString(expectedCoinbaseMessageBytes), Arrays.toString(bitcoinMergedMiningCoinbaseTransactionTail)); return false; } /* * We check that the there is no other block before the rsk tag, to avoid a possible malleability attack: * If we have a mid state with 10 blocks, and the rsk tag, we can also have * another mid state with 9 blocks, 64bytes + the rsk tag, giving us two blocks with different hashes but the same spv proof. * */ if (rskTagPosition >= 64) { logger.warn("bitcoin coinbase transaction tag position is bigger than expected 64. Actual: {}.", Integer.toString(rskTagPosition)); return false; } List<Byte> rskTagAsList = Arrays.asList(ArrayUtils.toObject(RskMiningConstants.RSK_TAG)); int lastTag = Collections.lastIndexOfSubList(bitcoinMergedMiningCoinbaseTransactionTailAsList, rskTagAsList); if (rskTagPosition != lastTag) { logger.warn("The valid RSK tag is not the last RSK tag. Tail: {}.", Arrays.toString(bitcoinMergedMiningCoinbaseTransactionTail)); return false; } int remainingByteCount = bitcoinMergedMiningCoinbaseTransactionTail.length - rskTagPosition - RskMiningConstants.RSK_TAG.length - RskMiningConstants.BLOCK_HEADER_HASH_SIZE; if (remainingByteCount > RskMiningConstants.MAX_BYTES_AFTER_MERGED_MINING_HASH) { logger.warn("More than 128 bytes after RSK tag"); return false; } // TODO test long byteCount = Pack.bigEndianToLong(bitcoinMergedMiningCoinbaseTransactionMidstate, 8); long coinbaseLength = bitcoinMergedMiningCoinbaseTransactionTail.length + byteCount; if (coinbaseLength <= 64) { logger.warn("Coinbase transaction must always be greater than 64-bytes long. But it was: {}", coinbaseLength); return false; } SHA256Digest digest = new SHA256Digest(bitcoinMergedMiningCoinbaseTransactionMidstate); digest.update(bitcoinMergedMiningCoinbaseTransactionTail, 0, bitcoinMergedMiningCoinbaseTransactionTail.length); byte[] bitcoinMergedMiningCoinbaseTransactionOneRoundOfHash = new byte[32]; digest.doFinal(bitcoinMergedMiningCoinbaseTransactionOneRoundOfHash, 0); Sha256Hash bitcoinMergedMiningCoinbaseTransactionHash = Sha256Hash .wrapReversed(Sha256Hash.hash(bitcoinMergedMiningCoinbaseTransactionOneRoundOfHash)); if (!mpValidator.isValid(bitcoinMergedMiningBlock.getMerkleRoot(), bitcoinMergedMiningCoinbaseTransactionHash)) { logger.warn("bitcoin merkle branch doesn't match coinbase and state root"); return false; } return true; }
From source file:com.facebook.delegatedrecovery.CountersignedRecoveryToken.java
License:Open Source License
/** * Utility method to quickly get a hex-encoded SHA256 digest of the data field * of the countersigned token, which contains the original token. * /*from www . ja v a 2 s . c om*/ * @return hex encoded string of SHA256 digest */ public String getInnerTokenHash() { final SHA256Digest digest = new SHA256Digest(); final byte[] hash = new byte[digest.getByteLength()]; digest.update(data, 0, data.length); digest.doFinal(hash, 0); return DelegatedRecoveryUtils.encodeHex(hash); }
From source file:com.facebook.delegatedrecovery.DelegatedRecoveryUtils.java
License:Open Source License
/** * Simple utility method to return a hex-encoded string of the SHA256 digest * of a byte[]//from w w w . j a v a 2s . c o m * * @param bytes The bytes to encode * @return The hex encoded bytes in a String */ public static String sha256(final byte[] bytes) { // hash of the token to re-identify it later final SHA256Digest digest = new SHA256Digest(); final byte[] hash = new byte[digest.getByteLength()]; digest.update(bytes, 0, bytes.length); digest.doFinal(hash, 0); return DelegatedRecoveryUtils.encodeHex(hash); }
From source file:com.facebook.delegatedrecovery.RecoveryToken.java
License:Open Source License
private byte[] getSignature(final byte[] rawArray, final ECPrivateKey privateKey) throws IOException { if (this.signature != null) { throw new IllegalStateException("This token already has a signature."); }/*from w ww. ja v a 2s . c o m*/ final BigInteger privatePoint = privateKey.getS(); final SHA256Digest digest = new SHA256Digest(); final byte[] hash = new byte[digest.getByteLength()]; digest.update(rawArray, 0, rawArray.length); digest.doFinal(hash, 0); final ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest())); signer.init(true, new ECPrivateKeyParameters(privatePoint, DelegatedRecoveryUtils.P256_DOMAIN_PARAMS)); final BigInteger[] signature = signer.generateSignature(hash); final ByteArrayOutputStream s = new ByteArrayOutputStream(); final DERSequenceGenerator seq = new DERSequenceGenerator(s); seq.addObject(new ASN1Integer(signature[0])); seq.addObject(new ASN1Integer(signature[1])); seq.close(); return s.toByteArray(); }
From source file:com.github.horrorho.inflatabledonkey.file.KeyBlobCurve25519Unwrap.java
License:Open Source License
public static Optional<byte[]> curve25519Unwrap(byte[] myPublicKey, byte[] myPrivateKey, byte[] otherPublicKey, byte[] wrappedKey) { SHA256Digest sha256 = new SHA256Digest(); byte[] shared = Curve25519.agreement(otherPublicKey, myPrivateKey); logger.debug("-- curve25519Unwrap() - shared agreement: 0x{}", Hex.toHexString(shared)); // Stripped down NIST SP 800-56A KDF. byte[] counter = new byte[] { 0x00, 0x00, 0x00, 0x01 }; byte[] hash = new byte[sha256.getDigestSize()]; sha256.reset();// ww w .j ava2 s . c o m sha256.update(counter, 0, counter.length); sha256.update(shared, 0, shared.length); sha256.update(otherPublicKey, 0, otherPublicKey.length); sha256.update(myPublicKey, 0, myPublicKey.length); sha256.doFinal(hash, 0); logger.debug("-- curve25519Unwrap() - kek: {}", Hex.toHexString(hash)); return RFC3394Wrap.unwrapAES(hash, wrappedKey); }
From source file:com.github.horrorho.inflatabledonkey.pcs.xfile.FileKeyAssistant.java
License:Open Source License
public static Optional<byte[]> curve25519Unwrap(byte[] myPublicKey, byte[] myPrivateKey, byte[] otherPublicKey, byte[] wrappedKey) { SHA256Digest sha256 = new SHA256Digest(); byte[] shared = Curve25519.agreement(otherPublicKey, myPrivateKey); byte[] pad = new byte[] { 0x00, 0x00, 0x00, 0x01 }; byte[] hash = new byte[sha256.getDigestSize()]; sha256.reset();/*from w w w . j ava 2 s. c om*/ sha256.update(pad, 0, pad.length); sha256.update(shared, 0, shared.length); sha256.update(otherPublicKey, 0, otherPublicKey.length); sha256.update(myPublicKey, 0, myPublicKey.length); sha256.doFinal(hash, 0); return AESWrap.unwrap(hash, wrappedKey); }
From source file:com.github.horrorho.liquiddonkey.cloud.keybag.FileKeyFactory.java
License:Open Source License
ByteString unwrapCurve25519(KeyBag keyBag, int protectionClass, ByteString key, AESWrap aesWrap, SHA256Digest sha256) { if (key.size() != 0x48) { logger.warn("-- unwrapCurve25519() > bad key length: {}", Bytes.hex(key)); return null; }/*w ww . ja v a 2 s .c o m*/ byte[] myPrivateKey = keyBag.classKey(protectionClass, "KEY").toByteArray(); if (myPrivateKey == null) { logger.warn("-- unwrapCurve25519() > no KEY key for protection class: {}", protectionClass); return null; } byte[] myPublicKey = keyBag.classKey(protectionClass, "PBKY").toByteArray(); if (myPublicKey == null) { logger.warn("-- unwrapCurve25519() > no PBKY key for protection class: {}", protectionClass); return null; } byte[] otherPublicKey = key.substring(0, 32).toByteArray(); byte[] shared = Curve25519.create().agreement(otherPublicKey, myPrivateKey); byte[] pad = new byte[] { 0x00, 0x00, 0x00, 0x01 }; byte[] hash = new byte[sha256.getDigestSize()]; sha256.reset(); sha256.update(pad, 0, pad.length); sha256.update(shared, 0, shared.length); sha256.update(otherPublicKey, 0, otherPublicKey.length); sha256.update(myPublicKey, 0, myPublicKey.length); sha256.doFinal(hash, 0); try { return ByteString.copyFrom(aesWrap.unwrap(hash, key.substring(0x20, key.size()).toByteArray())); } catch (IllegalStateException | InvalidCipherTextException ex) { logger.warn("-- unwrapCurve25519() > failed to unwrap key: {} protection class: {} exception: {}", Bytes.hex(key), protectionClass, ex); return null; } }
From source file:com.ipseorama.webapp.baddtls.CertHolder.java
public static String getPrint(org.bouncycastle.asn1.x509.Certificate fpc) throws IOException { StringBuilder b = new StringBuilder(); byte[] enc = fpc.getEncoded(); SHA256Digest d = new SHA256Digest(); d.update(enc, 0, enc.length);//from w w w . j a va 2 s . c om byte[] result = new byte[d.getDigestSize()]; d.doFinal(result, 0); for (byte r : result) { String dig = Integer.toHexString((0xff) & r).toUpperCase(); if (dig.length() == 1) { b.append('0'); } b.append(dig).append(":"); } b.deleteCharAt(b.length() - 1); return b.toString(); }
From source file:de.tsenger.animamea.crypto.KeyDerivationFunction.java
License:Open Source License
/** * Erzeugt AES-256 Schlssel/*from w w w . ja va 2 s . c o m*/ * * @return Schlssel als Byte-Array */ public byte[] getAES256Key() { byte[] checksum = new byte[32]; SHA256Digest sha256 = new SHA256Digest(); sha256.update(mergedData, 0, mergedData.length); sha256.doFinal(checksum, 0); return checksum; }