public byte[] encode(byte[] mHash, int emBits, byte[] salt) {
      int sLen = salt.length;

      // 1. If the length of M is greater than the input limitation for the hash
      // function (2**61 - 1 octets for SHA-1) then output "message too long"
      // and stop.
      // 2. Let mHash = Hash(M), an octet string of length hLen.
      if (hLen != mHash.length) {
         throw new IllegalArgumentException("wrong hash");
      }
      // 3. If emBits < 8.hLen + 8.sLen + 9, output 'encoding error' and stop.
      if (emBits < (8*hLen + 8*sLen + 9)) {
         throw new IllegalArgumentException("encoding error");
      }
      int emLen = (emBits + 7) / 8;
      // 4. Generate a random octet string salt of length sLen; if sLen = 0,
      // then salt is the empty string.
      // ...passed as argument to accomodate JCE
      // 5. Let M0 = 00 00 00 00 00 00 00 00 || mHash || salt;
      // M0 is an octet string of length 8 + hLen + sLen with eight initial zero
      // octets.
      // 6. Let H = Hash(M0), an octet string of length hLen.
      byte[] H;
      int i;
      synchronized (hash) {
         for (i = 0; i < 8; i++) {
            hash.update((byte) 0x00);
         }
         hash.update(mHash, 0, hLen);
         hash.update(salt, 0, sLen);
         H = hash.digest();
      }
      // 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2
      // zero octets. The length of PS may be 0.
      // 8. Let DB = PS || 01 || salt.
      byte[] DB = new byte[emLen - sLen - hLen - 2 + 1 + sLen];
      DB[emLen - sLen - hLen - 2] = 0x01;
      System.arraycopy(salt, 0, DB, emLen - sLen - hLen - 1, sLen);
      // 9. Let dbMask = MGF(H, emLen - hLen - 1).
      byte[] dbMask = MGF(H, emLen - hLen - 1);
      if (DEBUG && debuglevel > 8) {
         debug("dbMask (encode): "+Util.toString(dbMask));
         debug("DB (encode): "+Util.toString(DB));
      }
      // 10. Let maskedDB = DB XOR dbMask.
      for (i = 0; i < DB.length; i++) {
         DB[i] = (byte)(DB[i] ^ dbMask[i]);
      }
      // 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in
      // maskedDB to zero.
      DB[0] &= (0xFF >>> (8*emLen - emBits));
      // 12. Let EM = maskedDB || H || bc, where bc is the single octet with
      // hexadecimal value 0xBC.
      byte[] result = new byte[emLen];
      System.arraycopy(DB, 0, result, 0,                emLen - hLen - 1);
      System.arraycopy(H,  0, result, emLen - hLen - 1, hLen);
      result[emLen - 1] = (byte) 0xBC;
      // 13. Output EM.
      return result;
   }