title: Cipher.unwrap() key length Sun - BouncyCastle compatibility
body: <p>I have some JDK 1.6 code I'm porting to Android, and it's behaving differently.</p>
  
  <pre><code>// decode public key
  pubk = KeyFactory.getInstance("RSA").generatePublic(
      new X509EncodedKeySpec(X)
  );
  // decode symmetric key
  cipher = Cipher.getInstance("RSA");
  cipher.init(Cipher.UNWRAP_MODE, pubk);
  skey = (SecretKey)cipher.unwrap(key1, "AES", Cipher.SECRET_KEY);
  </code></pre>
  
  <p><code>pubk</code> is 2048-bit RSA key, though in different representations (Sun or OpenSSL).<br>
  <code>key1</code> is 2048-bit byte array.</p>
  
  <p><strong>Problem is:</strong> I have different results for <code>skey</code>. On Sun JRE it is 128-bit AES key, on Android it is 2048-bit array, <strong>containing following bytes:<br>
  [1, -1, -1 ... ,-1, 0, (actual key bytes here)]</strong></p>
  
  <p>Original wrapping is done the following way:</p>
  
  <pre><code>        // generate symmetric key
          kgen = KeyGenerator.getInstance("AES");
          kgen.init(128, SecureRandom.getInstance("SHA1PRNG"));
          skey = kgen.generateKey();
  
          // create Cipher
          cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
          cipher.init(Cipher.ENCRYPT_MODE, skey);
  
          // decode private key
          privk = KeyFactory.getInstance("RSA").generatePrivate(
              new PKCS8EncodedKeySpec(X)
          );
  
          // wrap symmetric key
          cipher = Cipher.getInstance("RSA");
          cipher.init(Cipher.WRAP_MODE, privk);
          skey_buffer = cipher.wrap(skey);  
  </code></pre>
  
  <p>During wrapping (in Sun JRE) <code>skey</code> is 128 bit, resulting <code>skey_buffer</code> is 2048 bit</p>
  
  <p><s>I suppose it has something to do with Sun's restrictions of key length to 128-bit. </s> Now I suppose it has something to do with padding. But how do I apply such restrictions to BouncyCastle implementation, to get the same unwrapped key output? Sure I can hardcode cutting out that <code>-1</code>'s at the beginning of decoded array, but maybe there are some (padding) parameters that can get original 128-bit text?</p>
  
  <p><strong>Upd:</strong> I was not attentive, and missed the fact unwrapped <code>skey</code> was not 256-bit, but 2048-bit. Updated question.</p>