Java tutorial
//package com.java2s; import java.io.ByteArrayOutputStream; public class Main { public static final byte[] FirstPadding = { (byte) 0x80 }; public static final byte[] ZeroPadding = { (byte) 0x00 }; public static byte[] padding(byte[] source) throws Exception { if (source.length >= 0x2000000000000000l) { throw new Exception(); } long l = source.length * 8; long k = 448 - (l + 1) % 512; if (k < 0) { k = k + 512; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(source); baos.write(FirstPadding); long i = k - 7; while (i > 0) { baos.write(ZeroPadding); i -= 8; } baos.write(long2bytes(l)); return baos.toByteArray(); } public static byte[] long2bytes(long l) { byte[] bytes = new byte[8]; for (int i = 0; i < 8; i++) { bytes[i] = (byte) (l >>> ((7 - i) * 8)); } return bytes; } public static byte[] toByteArray(int a, int b, int c, int d, int e, int f, int g, int h) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(32); baos.write(toByteArray(a)); baos.write(toByteArray(b)); baos.write(toByteArray(c)); baos.write(toByteArray(d)); baos.write(toByteArray(e)); baos.write(toByteArray(f)); baos.write(toByteArray(g)); baos.write(toByteArray(h)); return baos.toByteArray(); } public static byte[] toByteArray(int i) { byte[] byteArray = new byte[4]; byteArray[0] = (byte) (i >>> 24); byteArray[1] = (byte) ((i & 0xFFFFFF) >>> 16); byteArray[2] = (byte) ((i & 0xFFFF) >>> 8); byteArray[3] = (byte) (i & 0xFF); return byteArray; } }