title: Windows 8 Metro RSA Encryption: AsymmetricKeyAlgorithmProvider ImportPublicKey Fails
body: <p>I am attempting to pass some encrypted data between a Win 8 Metro app and a RESTful WCF service. Initially the Metro app requests a public key and the WCF service returns it as a raw Stream as to avoid any pesky formatting issues. The Base 64 encoded public key is decoded in the metro app into a byte array. Here is where the problem occurs. When I attempted to call AsymmetricKeyAlgorithmProvider.ImportPublicKey I get the error "ASN1 bad tag value met".</p>
  
  <p>I am using RSA PKCS1 for the encryption. Here is the relevant code:</p>
  
  <p><strong>WCF Service</strong></p>
  
  <pre><code>     string keyName = "This is passed in via a parameter";
       var key = !CngKey.Exists(keyName) ? CngKey.Create(CngAlgorithm2.Rsa, keyName) : CngKey.Open(keyName);
  
       // Create the RSA container to get keys and then dispose
       using (var rsaCng = new RSACng(key) { EncryptionPaddingMode = AsymmetricPaddingMode.Pkcs1, KeySize = 2048 })
       {
          byte[] publicBlob = rsaCng.Key.Export(CngKeyBlobFormat.GenericPublicBlob);
          publicKey = Convert.ToBase64String(publicBlob);
       }
  </code></pre>
  
  <p><strong>Metro App</strong></p>
  
  <pre><code>  public static string Encrypt(IBuffer dataBuffer, string publicKeyString)
    {
       var asymmAlg = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
       // The next line fails with ASN1 bad tag value met
       var publicKey = asymmAlg.ImportPublicKey(CryptographicBuffer.DecodeFromBase64String(publicKeyString), CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);
  
       var encryptedData = CryptographicEngine.Encrypt(publicKey, dataBuffer, null);
       return CryptographicBuffer.EncodeToBase64String(encryptedData);
    }
  </code></pre>
  
  <p><strong>EDIT 1: More information below</strong></p>
  
  <p>Exporting the public key from a 2048bit key pair from the WCF service yields a 283 bit length key blob, while exporting the same type of public key from the Metro app is only 270 bits. When I import the Metro generated public key it succeeds. Any idea why the WCF service has 13 extra bits on its public key? I think those extra 13 bits are causing the failure.</p>
  
  <p>Here is the Metro code that yields the shorter public key blob:</p>
  
  <pre><code>var provider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
  CryptographicKey standardKeyPair = provider.CreateKeyPair(2048);
  byte[] standardKey = standardKeyPair.ExportPublicKey(CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey).ToArray();
  </code></pre>