2017-07-04 139 views
1

我有桌面C#代碼(控制檯,WPF等),它從base64字符串生成密鑰並由其加密。在RSA算法中使用公鑰

string b64Key = ""; 
byte[] decoded = Convert.FromBase64String(b64Key); 
int modLength = BitConverter.ToInt32(decoded.Take(4).Reverse().ToArray(), 0); 
byte[] mod = decoded.Skip(4).Take(modLength).ToArray(); 
int expLength = BitConverter.ToInt32(decoded.Skip(modLength + 4).Take(4).Reverse().ToArray(), 0); 
byte[] exponent = decoded.Skip(modLength + 8).Take(expLength).ToArray(); 

RSAParameters key = new RSAParameters(); 
key.Modulus = mod; 
key.Exponent = exponent; 

var provider = new RSACryptoServiceProvider(); 
provider.ImportParameters(key); 
var encrypted = provider.Encrypt(Encoding.UTF8.GetBytes("string"), true); 

我必須在UWP項目中重用這部分代碼。

我嘗試過很多方法,但每一次我趕上當我試圖導入公鑰異常:

// try to use DESKTOP key for understanding 
byte[] mod = key.Modulus; 
byte[] exponent = key.Exponent; 
// this method concat arrays 
var buf = this.Combine(mod, exponent); 

// try to create key buffer from array 
IBuffer keyBuffer = CryptographicBuffer.CreateFromByteArray(buf); 
// try to create key buffer from base64 string 
keyBuffer = CryptographicBuffer.DecodeFromBase64String("base64 string"); 

var provider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1); 
var publicKey = provider.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey); 
// I tried all values in 'CryptographicPublicKeyBlobType' enum 

var encryptData = CryptographicEngine.Encrypt(publicKey, CryptographicBuffer.ConvertStringToBinary("string", BinaryStringEncoding.Utf8), null); 

我怎樣才能正確導入密鑰的UWP項目?

謝謝!

+0

什麼是例外情況,並在哪條線上下襬? – rene

+0

@rene它總是在我調用'ImportPublicKey'方法時發生。有幾種例外情況: 1.符合ASN1錯誤標記值。 (來自HRESULT的異常:0x8009310B) 2.異常來自HRESULT:0x90090005 –

回答

0

在第一個 - 我只有正確的模數和所有。我的base64字符串是不正確的公鑰(在這個字符串中的鍵,但有很多其他項目)。 之後,我發現只有一個從模數和指數生成公鑰的正確方法 - >將它們組合起來。但我仍然有例外。之後,我嘗試生成默認密鑰並更改其中的模數部分 - >並且它工作正常!

  var provider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaOaepSha1); 
      // create custom (random) key with size '1024' 
      var standardKeyPair = provider.CreateKeyPair(1024); 
      // export publick key to this default key 
      var standardBuffer = standardKeyPair.ExportPublicKey(CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey); 
      // copy it to bytes array 
      byte[] standardKey; 
      CryptographicBuffer.CopyToByteArray(standardBuffer, out standardKey); 

      // change part of the key to our modules 
      // I DON'T KNOW WHY, but starndart key has 7 bytes in prefix and 5 in suffix (nail) 
      // we have 128 bytes in modulus and 140 in default key -> so we must make 140 bytes from our modulus 
      Array.Copy(modulus, 0, standardKey, 7, modulus.Length);