1. Java example

public static String calculateVerificationCode(byte[] digestValue) throws
  NoSuchAlgorithmException {
    byte[] digest = MessageDigest.getInstance("SHA-256").digest(digestValue);
    ByteBuffer byteBuffer = ByteBuffer.wrap(digest);
    int shortBytes = Short.SIZE / Byte.SIZE; // Short.BYTES in java 8+
    int rightMostBytesIndex = byteBuffer.limit() - shortBytes;
    short twoRightMostBytes = byteBuffer.getShort(rightMostBytesIndex);
    int positiveInteger = twoRightMostBytes & 0xffff;
    String code = String.valueOf(positiveInteger);
    String paddedCode = "0000" + code;
    return paddedCode.substring(code.length());
}

Did this page help you?