/// <inheritdoc/> public ICryptographicKey ImportKeyPair(byte[] keyBlob, CryptographicPrivateKeyBlobType blobType = CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo) { Requires.NotNull(keyBlob, nameof(keyBlob)); RSAParameters parameters = KeyFormatter.GetFormatter(blobType) .Read(keyBlob) .ComputeFullPrivateKeyData(); IPrivateKey? privateKey = null; IPublicKey? publicKey = null; BigInteger? modulus = null, d = null, publicExponent = null; RSAPrivateKeySpec?privateKeySpec = null; RSAPublicKeySpec? publicKeySpec = null; try { #pragma warning disable CA2000 // Dispose objects before losing scope modulus = new BigInteger(1, parameters.Modulus); d = new BigInteger(1, parameters.D); privateKeySpec = new RSAPrivateKeySpec(modulus, d); var factory = KeyFactory.GetInstance("RSA"); if (factory is null) { throw new InvalidOperationException(Strings.UnsupportedAlgorithm); } privateKey = factory.GeneratePrivate(privateKeySpec) !; var privateRsaKey = privateKey.JavaCast <IRSAPrivateKey>() !; publicExponent = new BigInteger(1, parameters.Exponent); publicKeySpec = new RSAPublicKeySpec(privateRsaKey.Modulus, publicExponent); publicKey = factory.GeneratePublic(publicKeySpec) !; return(new RsaCryptographicKey(publicKey, privateKey, parameters, this.algorithm)); #pragma warning restore CA2000 // Dispose objects before losing scope } catch { publicExponent?.Dispose(); publicKeySpec?.Dispose(); privateKeySpec?.Dispose(); modulus?.Dispose(); d?.Dispose(); privateKey?.Dispose(); publicKey?.Dispose(); throw; } }
/// <inheritdoc/> public ICryptographicKey ImportPublicKey(byte[] keyBlob, CryptographicPublicKeyBlobType blobType = CryptographicPublicKeyBlobType.X509SubjectPublicKeyInfo) { Requires.NotNull(keyBlob, nameof(keyBlob)); var parameters = KeyFormatter.GetFormatter(blobType).Read(keyBlob); BigInteger? modulus = null, exponent = null; RSAPublicKeySpec?spec = null; try { #pragma warning disable CA2000 // Dispose objects before losing scope modulus = new BigInteger(1, parameters.Modulus); exponent = new BigInteger(1, parameters.Exponent); spec = new RSAPublicKeySpec(modulus, exponent); #pragma warning restore CA2000 // Dispose objects before losing scope KeyFactory?factory = KeyFactory.GetInstance("RSA"); if (factory is null) { throw new InvalidOperationException(Strings.UnsupportedAlgorithm); } IPublicKey?publicKey = factory.GeneratePublic(spec); if (publicKey is null) { throw new InvalidOperationException("KeyFactory.GeneratePublic returned null."); } return(new RsaCryptographicKey(publicKey, parameters, this.algorithm)); } catch { spec?.Dispose(); modulus?.Dispose(); exponent?.Dispose(); throw; } }