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項目?
謝謝!
什麼是例外情況,並在哪條線上下襬? – rene
@rene它總是在我調用'ImportPublicKey'方法時發生。有幾種例外情況: 1.符合ASN1錯誤標記值。 (來自HRESULT的異常:0x8009310B) 2.異常來自HRESULT:0x90090005 –