title: How to hash multiple times and concatenate a string in each round
body: <p>I am writing a program which concatenate a word <code>R</code> at the end of a password and then calculate the SHA-256 hash. Later on, adding the <code>R</code> word again at the end of the hex result and calculate the new hash with SHA256.</p>
  
  <p>I want this to repeat for 100 times. Every time I want to print the hash.</p>
  
  <p>So something like this, in pseudo code:</p>
  
  <pre><code>hash = SHA256(...(SHA256(SHA256(“password”||R)||R)||R)..)
  </code></pre>
  
  <p>I am currently testing my code by hashing 2 times: </p>
  
  <pre><code>   String R = "f@ghj!$g";
     hash = password.concat(R);
  
     MessageDigest md = MessageDigest.getInstance("SHA-256");
     digest = hash.getBytes(StandardCharsets.UTF_8);
  
     for (int i=0;i&lt;2;i++) {
  
       md.update(digest);
       digest = md.digest();
  
       hash = String.format("%064x", new BigInteger(1,digest)).concat(R);
       System.out.println(hash);
  
       digest = hash.getBytes(StandardCharsets.UTF_8);
     }
  </code></pre>
  
  <hr>
  
  <p>Lets forget this concatenation for a sec.</p>
  
  <p>For example can't understand why the following two codes produce different results:</p>
  
  <p>Code 1:</p>
  
  <pre><code>   for (int i=0;i&lt;2;i++) {
  
       md.update(digest);
       digest = md.digest();
  
     }
  
   hash = String.format("%064x", new BigInteger(1,digest));   
   System.out.println(hash);
  </code></pre>
  
  <p>Code 2:</p>
  
  <pre><code>   for (int i=0;i&lt;2;i++) {
  
       md.update(digest);
       digest = md.digest();
       //convert hash to string
       hash = String.format("%064x", new BigInteger(1,digest));
       //convert string again to bytes
       digest = hash.getBytes(StandardCharsets.UTF_8);
     }
  
   System.out.println(hash);
  </code></pre>
  
  <p>My question is: which is the right way to decode the hash (<code>Byte[]</code>) into hex String every time to concatenate the <code>R</code> word and encode again into bytes the right way?</p>