title: Generating and securing gift card codes
body: <p>I'm working for a company that is generating gift card codes which can be used to pay for goods on online stores. </p>
  
  <p>I'm wondering what the most secure way of generating these gift card codes are. The length needs to be 16 characters (though that is negotiable) and can be alphanumeric (though numeric would be more customer friendly). </p>
  
  <p>From what I can see, the most secure way to do this is generate a gift card code of a specific length with the following Java code:</p>
  
  <pre><code>static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  static SecureRandom rnd = new SecureRandom();
  
  String randomString( int len ){
     StringBuilder sb = new StringBuilder( len );
     for( int i = 0; i &lt; len; i++ ) 
        sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
     return sb.toString();
  }
  </code></pre>
  
  <p>This is taken from the SO answer <a href="https://stackoverflow.com/a/157202/1246159">here</a>. I removed the lowercase letters from the string to make it more user friendly. So this produces 36 ^ 16 combinations. Numeric alone would be 10 ^ 16 combinations. I believe numeric alone would be enough but it's often stressed that, given the increasing prevalence of gift card fraud, the string should be alphanumeric.</p>
  
  <p><strong>So that's question one: numeric or alphanumeric?</strong></p>
  
  <p>When users use the gift cards on an online store to pay for goods, a call is made to our API which returns the balance and currency for that gift card. Given that the gift card codes are entered on 3rd party servers, these gift cards are now available to people with access to those servers. This is obviously a problem in the case where there is still a balance left after a user has partially redeemed one.</p>
  
  <p>One option would be to, when the call to our API is made (with the gift card code) to get the balance, we return and save on their store a random string which can only be used by the online store when they are billing us - we will match that with the gift card code on our system. The problem with that is presumably the gift card code the user enters on checkout gets logged somewhere in their logs, and is accessible to anyone with access to those logs. </p>
  
  <p>Another option is that we refresh the gift card code after it is partially redeemed. So the user essentially gets issued with a new gift card code for the balance and the previous one is cancelled. This is probably the most secure, but not that user friendly.</p>
  
  <p><strong>So that's the second question: how do we secure gift card codes that are only partially redeemed and still have value left on them?</strong></p>