Java Code Examples for org.bouncycastle.jcajce.provider.digest.SHA256

Following code examples demonstrate how to use org.bouncycastle.jcajce.provider.digest.SHA256from android. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use org.bouncycastle.jcajce.provider.digest.SHA256and various code implementation of this class.

    private String checksum(InputStream is) throws IOException {
        SHA256.Digest hash = new SHA256.Digest();
        int nRead;
        byte[] data = new byte[16384];

        while ((nRead = is.read(data, 0, data.length)) != -1) {
            hash.update(data, 0, nRead);
        }
        return Base64.toBase64String(hash.digest());
    } 


    public void doof() {
        Git.cloneRepository();
        new SHA256.Digest();
        try {
            Git git = Git.open(new File("."));
            git.commit().call();
        } catch (IOException | UnmergedPathsException | WrongRepositoryStateException e) {
            e.printStackTrace();
        } catch (ConcurrentRefUpdateException e) {
            e.printStackTrace();
        } catch (RejectCommitException e) {
            e.printStackTrace();
        } catch (NoHeadException e) {
            e.printStackTrace();
        } catch (NoMessageException e) {
            e.printStackTrace();
        } catch (GitAPIException e) {
            e.printStackTrace();
        }

    } 

    public AuthmeSHA(String algorithm) {
        switch(algorithm.toLowerCase()) {
            case "sha256":
                this.digest = new SHA256.Digest();
                this.prefix = "SHA";
                break;
            default:
                throw new IllegalArgumentException("Unknown SHA digest: " + algorithm);
        }
    } 

    static public String encode(byte[] privateKey){

        byte[] WIFByte=new byte[privateKey.length+2+4];

        try {
            MessageDigest sha256=MessageDigest.getInstance("SHA-256");

            WIFByte[0]=(byte)0x80;

            WIFByte[WIFByte.length-5]=(byte)0x01;

            for(int i=0;i<privateKey.length;i++){
                WIFByte[i+1]=privateKey[i];
            }

            byte[] part=Arrays.copyOf(WIFByte,WIFByte.length-4);

            byte[] double_hash=sha256.digest(sha256.digest(part));

            WIFByte[WIFByte.length-1]=double_hash[3];
            WIFByte[WIFByte.length-2]=double_hash[2];
            WIFByte[WIFByte.length-3]=double_hash[1];
            WIFByte[WIFByte.length-4]=double_hash[0];

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException("Cannot get Instance of SHA-256 digest");
        }
        return Base58.encode(WIFByte);
    } 

	private Block generateGenesisBlock(){
		Block genesis = new Block();
		genesis.setIndex(0);
		genesis.setDifficulty(NETWORK_DIFICULTY);
		genesis.setPrevBlockHash("");
		genesis.setMinedBy(this.wallet.getAddress());
		Transaction ico = this.wallet.sign(this.wallet.getAddress(), 1000000, 0);
		ico.setAddressFrom("");
		ico.setMinedInBlockIndex(1);
		ico.setPaid(true);
		genesis.getTransactions().add(ico);
		
		
		
		String blockData = String.valueOf(genesis.getIndex());
		
		for (Iterator iterator = genesis.getTransactions().iterator(); iterator.hasNext();) {
			Transaction tr = (Transaction) iterator.next();
			blockData += tr.toString();
		}
		
		blockData += genesis.getDifficulty();
		blockData += genesis.getPrevBlockHash();
		blockData += genesis.getMinedBy();
		
		MessageDigest sha256 = new SHA256.Digest();
		byte[] hashedData = sha256.digest(blockData.getBytes());
		
		String blockDataHash = Hex.toHexString(hashedData);
		
		
		boolean isBlockMined = false;
		while(isBlockMined == false){
			int dificulty = NETWORK_DIFICULTY;
			this.currentTime = System.currentTimeMillis();
			this.nonce++;
			byte[] hash = sha256.digest((blockDataHash + String.valueOf(currentTime) + String.valueOf(this.nonce)).getBytes());
			this.currentHash = Hex.toHexString(hash);
			if(this.currentHash.substring(0, dificulty).equals(new String(new char[dificulty]).replace('\0', '0'))){
				isBlockMined = true;
			}

		}

		genesis.setBlockHash(this.currentHash);
		genesis.setCreatedTimestamp(this.currentTime);
		genesis.setNonce(this.nonce);
		
		return genesis;
	} 

    public static void main(String[] args) {
        createPasswordHash(new SHA3.Digest224());
        createPasswordHash(new SHA3.Digest256());
        createPasswordHash(new SHA3.Digest384());
        createPasswordHash(new SHA3.Digest512());
        final Password passwordHash = new Password("test", createPasswordHash(new SHA256.Digest()));

        EncryptionProvider provider = new DigestEncryption(new SHA256.Digest(), 1);
        final byte[] response = provider.response(passwordHash, "a".getBytes());
        System.out.println(bytesToHex(response));
    } 

        public String hash() {
            SHA256.Digest sha256 = new SHA256.Digest();
            sha256.update(token_nonce.toByteArray());
            sha256.update(from_address.getBytes());
            sha256.update(to_address.getBytes());
            sha256.update(signature.r.toByteArray());
            sha256.update(signature.s.toByteArray());
            return new BigInteger(1, sha256.digest()).toString(16);
        } 

    public static void main(String[] args) {
        Random rand = new Random();
        EncryptionParams params = EncryptionParams.newTestParams(rand, CryptoConstants.CURVE, CryptoConstants.DIGEST);

        System.out.println("Test various hash strategies...");
        System.out.println("  (warming up the jit, this may take a few seconds)");

        for (int i = 0; i < N_POINTS_TO_HASH; i++) {
            pointToHash[i] = params.getGenerator().multiply(params.getRandomIndex());
        }

        testUnit(params, new SHA3.Digest256());
        testUnit(params, new SHA1.Digest());
        testUnit(params, new SHA256.Digest());
    } 

    private static HMac sha512Digest(byte[] key) {
        HMac hMac = new HMac(new SHA512Digest());
        hMac.init(new KeyParameter(key));
        return hMac;
    } 

    public String getUri() {
        RemoteHandshake handshake = getRemoteHandshake();
        String uri = handshake.getWsUri() + "?auth=";
        String s = handshake.getSalt();
        if (s != null) {
            byte[] salt = handshake.getSalt().getBytes(CharsetUtil.UTF_8);
            byte[] sharedSecret = handshake.getRemoteKey().getSharedSecret();

            byte[] bytes = new byte[salt.length + sharedSecret.length];
            System.arraycopy(salt, 0, bytes, 0, salt.length);
            System.arraycopy(sharedSecret, 0, bytes, salt.length, sharedSecret.length);

            SHA256.Digest sha = new SHA256.Digest();
            byte[] digested = sha.digest(bytes);
            uri += UrlBase64.encode(digested);
        } else {
            uri += "_";
        }

        String token = getLocalHandshake().getToken();
        if (token != null) {
            uri += "&token=" + token;
        }

        uri += "&format=" + handshake.getFormat().toJson();
        uri += "&dsId=" + getLocalHandshake().getDsId();
        return uri;
    } 

	public String calculateBlockDataHash(Block blockToMine) {
		String blockData = String.valueOf(blockToMine.getIndex());
		
		for (Iterator iterator = blockToMine.getTransactions().iterator(); iterator.hasNext();) {
			Transaction tr = (Transaction) iterator.next();
			blockData += tr.toString();
		}
		
		blockData += blockToMine.getDifficulty();
		blockData += blockToMine.getPrevBlockHash();
		blockData += blockToMine.getMinedBy();
		
		MessageDigest sha256 = new SHA256.Digest();
		byte[] hashedData = sha256.digest(blockData.getBytes());
		
		String blockDataHash = Hex.toHexString(hashedData);
		return blockDataHash;
	} 

	private boolean mine(MiningJob miningJob){
		String dataHash = calculateBlockDataHash(miningJob.getBlockToMine());
		int dificulty = miningJob.getDifficulty();
		this.currentTime = System.currentTimeMillis();
		this.nonce++;
		MessageDigest sha256 = new SHA256.Digest();
		byte[] hashedData = sha256.digest((dataHash + String.valueOf(currentTime) + String.valueOf(this.nonce)).getBytes());
		this.currentHash = Hex.toHexString(hashedData);
		if(this.currentHash.substring(0, dificulty).equals(new String(new char[dificulty]).replace('\0', '0'))){
			return true;
		}else{
			return false;
		}
	} 

    public LocalHandshake(Configuration config) {
        if (config == null) {
            throw new NullPointerException("config");
        }

        config.validate();

        this.keys = config.getKeys();
        this.publicKey = keys.encodedPublicKey();
        String singleEncodedDsId = StringUtils.encodeName(config.getDsIdWithHash());
        this.dsId = singleEncodedDsId.replaceAll("%", "%25");
        this.isRequester = config.isRequester();
        this.isResponder = config.isResponder();
        this.linkData = config.getLinkData();
        this.zone = config.getZone();
        String token = config.getToken();
        if (token != null) {
            byte[] dsId = singleEncodedDsId.getBytes(CharsetUtil.UTF_8);
            byte[] fullToken = token.getBytes(CharsetUtil.UTF_8);
            byte[] bytes = new byte[dsId.length + fullToken.length];
            System.arraycopy(dsId, 0, bytes, 0, dsId.length);
            System.arraycopy(fullToken, 0, bytes, dsId.length, fullToken.length);

            SHA256.Digest sha = new SHA256.Digest();
            byte[] digested = sha.digest(bytes);
            String hash = UrlBase64.encode(digested);

            token = token.substring(0, 16) + hash;
        }
        this.token = token;
    } 

    public static void main(String[] args) {
        HMAC hmac = new HMAC();
        byte[] out = hmac.hmac("key".getBytes(), "The quick brown fox jumps over the lazy dog".getBytes(), new SHA256.Digest(), 64);
        System.out.println(Hex.toHexString(out));
    } 

    public String Sha2_256H(String input)  {
        SHA256.Digest SHA256 = new SHA256.Digest();
        byte[] digest = SHA256.digest(input.getBytes());

        return Hex.toHexString(digest);
    } 

    public String Sha2_256B(String input)  {
        SHA256.Digest SHA256 = new SHA256.Digest();
        byte[] digest = SHA256.digest(input.getBytes());
        BigInteger bigInt = new BigInteger(1, digest);
        String Bin = bigInt.toString(2);
        while (Bin.length() < 256) {
            Bin = "0" + Bin;
        }
        return Bin;
    } 

    }

    public void testDigest()
        throws Exception
    {
        evilNoConstructionTest(GOST3411.class);
        evilNoConstructionTest(MD2.class);
        evilNoConstructionTest(MD4.class);
        evilNoConstructionTest(MD5.class);
        evilNoConstructionTest(RIPEMD128.class);
        evilNoConstructionTest(RIPEMD160.class);
        evilNoConstructionTest(RIPEMD256.class);
        evilNoConstructionTest(RIPEMD320.class);
        evilNoConstructionTest(SHA1.class);
        evilNoConstructionTest(SHA224.class);
        evilNoConstructionTest(SHA256.class);
        evilNoConstructionTest(SHA384.class);
        evilNoConstructionTest(SHA3.class);
        evilNoConstructionTest(SHA512.class);
        evilNoConstructionTest(SM3.class);
        evilNoConstructionTest(Tiger.class);
        evilNoConstructionTest(Whirlpool.class);
    } 

        switch (oid) {
                return new MD2.Digest();
                return new MD5.Digest();
                return new SHA1.Digest();
                return new SHA224.Digest();
                return new SHA256.Digest();
                return new SHA384.Digest();
                return new SHA512.Digest();
                return new RIPEMD128.Digest();
                return new RIPEMD160.Digest();
                return new RIPEMD256.Digest();
                return new GOST3411.Digest();
            default:
                throw new NoSuchAlgorithmException(hashAlgorithm);
        } 

    public void getSha256TimeStamp() throws IOException {
        MessageDigest digest = new SHA256.Digest();

        String originalMessage = UUID.randomUUID().toString();
        digest.digest(TsaClient.hexStringToByteArray(originalMessage));

        TimeStampToken token = tsaClient.getTimeStampToken(originalMessage.getBytes());

        tsaClient.printTokenInfo(token);
        final FileOutputStream output = new FileOutputStream("tspResponse.bin");
        IOUtils.write(token.getEncoded(), output);
        output.close();
        digest.reset();
        System.out.println("Совпадение хэша сообщения и хэша в штампе времени: "+tsaClient.validateTokenTimestamp(token, digest.digest(originalMessage.getBytes())));
    } 

    public void hmacSHA256Test() throws Exception {
        HMAC hmac = new HMAC();
        byte[] out = 
                hmac.hmac("key".getBytes(), "The quick brown fox jumps over the lazy dog".getBytes(), new SHA256.Digest(), 64);
        assertEquals("f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8", Hex.toHexString(out));
    } 

	public static void main(String[] args) throws UnsupportedEncodingException {
		String pass = "Hello我是王小明";
		System.out.println(pass);

		DigestSHA3 sha3256 = new SHA3.Digest256();
		sha3256.update(pass.getBytes("UTF-8"));
		System.out.println(Hex.toHexString(sha3256.digest()));

		Digest sha256 = new SHA256.Digest();
		sha256.update(pass.getBytes("UTF-8"));
		byte[] d = sha256.digest();
		System.out.println(Hex.toHexString(d));
		sha256.reset();
		sha256.update(d);
		System.out.println(Hex.toHexString(sha256.digest()));
		
		sha3256.reset();
		sha3256.update(d);
		System.out.println(Hex.toHexString(sha3256.digest()));
	} 

    switch (variant) {
      case "SHA1":
        output = SHA256.Digest.getInstance("SHA-1", "BC").digest(input);
        break;
      case "SHA512":
        output = SHA256.Digest.getInstance("SHA-512", "BC").digest(input);
        break;
      case "SHA256":
      default:
        output = SHA256.Digest.getInstance("SHA-256", "BC").digest(input);
        break;
    } 

    private static void logState(StateAndRef<TradeState> state) {
        System.out.println("{Data: }"+ state.getState().getData());
        System.out.println("{Contract: }"+ state.getState().getContract());
        System.out.println("{Hash: }"+ state.getRef().getTxhash().toString());
        try{
            byte[] tradeStateAsBson = state.getState().getData().getTradeStateAsBson();
            BsonDocument bsonDocument = fromInputStream(new ByteArrayInputStream(tradeStateAsBson));
            byte [] payload = ((BsonBinary)bsonDocument.get("payload")).getData();
            BsonDocument bsonDocumentReal = fromInputStream(new ByteArrayInputStream(payload));
            System.out.println("{Trade payload: }"+ bsonDocumentReal.toString());
            BsonValue payloadhash = bsonDocument.get("payloadhash");
            System.out.println("{Trade payloadhash: }"+ payloadhash.asString().getValue());

            BsonDocument mongoDbDoc = new BsonDocument();
            mongoDbDoc.put("dataString", new BsonString(bsonDocumentReal.toString()));
            mongoDbDoc.put("dataBinary", new BsonBinary(payload));
            mongoDbDoc.put("hash", new BsonString(payloadhash.asString().getValue()));
            mongoDbDoc.put("contractId", new BsonString(UUID.randomUUID().toString()));

            MongoHelper mongoHelper = new MongoHelper();
            MongoDatabase cordaDb = mongoHelper.getDatabase();
            MongoCollection<BsonDocument> ledger = cordaDb.getCollection("ledger", BsonDocument.class);
            ledger.insertOne(mongoDbDoc);
            System.out.println("Bson Record Inserted in MongoDb");

            FindIterable<BsonDocument> bsonFromDB = ledger.find();
            MongoCursor<BsonDocument> bsonDocumentMongoCursor = bsonFromDB.iterator();
            try {
                while(bsonDocumentMongoCursor.hasNext()) {
                    BsonDocument document = bsonDocumentMongoCursor.next();
                    byte [] data = SHA256.Digest.getInstance("SHA256").digest(document.get("dataBinary").asBinary().getData());
                    System.out.println("From DB - dataBinary : "+document.getBinary("dataBinary").getData().toString());
                    System.out.println("From DB - hash: "+document.getString("hash"));
                    System.out.println("Applied SHA2 on dataBinary : "+data.toString());
                    StringBuffer stringBuffer = new StringBuffer();
                    for (byte bytes : data) {
                        stringBuffer.append(String.format("%02x", bytes & 0xff));
                    }
                    System.out.println("Converted SHA2 formatted data to Hex: "+stringBuffer.toString());

                    if(payloadhash.asString().getValue().equals(stringBuffer.toString())){
                        System.out.println("Hash stored in Corda Vault MATCHES WITH Hash of data stored in MongoDB");
                    }
                }
            } finally {
                bsonDocumentMongoCursor.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    } 

    public boolean validate(String auth) {
        if (auth == null) {
            return false;
        }
        byte[] origHash = UrlBase64.decode(auth);
        byte[] validHash;
        {
            byte[] salt = this.salt.getBytes(CharsetUtil.UTF_8);
            byte[] ss = RemoteKey.generate(tempKey, publicKey).getSharedSecret();
            byte[] bytes = new byte[salt.length + ss.length];
            System.arraycopy(salt, 0, bytes, 0, salt.length);
            System.arraycopy(ss, 0, bytes, salt.length, ss.length);

            SHA256.Digest sha = new SHA256.Digest();
            validHash = sha.digest(bytes);
        }
        return MessageDigest.isEqual(origHash, validHash);
    } 

Advertisement
Javadoc
PBEWithHmacSHA public static class PBEWithMacKeyFactory extends PBESecretKeyFactory { public PBEWith

MacKeyFactory() { super("PBEwithHmacSHA256", null, false, PKCS12, SHA256, 256, 0);

Read More
Advertisement