예제 #1
0
        /// <inheritdoc />
        public byte[] ExportPublicKey(CryptographicPublicKeyBlobType blobType)
        {
            byte[]        keyData    = KeyDataWithTag(GetPublicKeyIdentifierWithTag(this.keyIdentifier)).ToArray();
            RSAParameters parameters = KeyFormatter.Pkcs1.Read(keyData);

            return(KeyFormatter.GetFormatter(blobType).Write(parameters));
        }
예제 #2
0
    public void KeyPairInterop(CryptographicPrivateKeyBlobType blobType, AsymmetricAlgorithm algorithmName, string base64Key)
    {
        var    algorithm = WinRTCrypto.AsymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithmName);
        var    key       = algorithm.ImportKeyPair(Convert.FromBase64String(base64Key), blobType);
        var    p1        = KeyFormatter.GetFormatter(blobType).Read(Convert.FromBase64String(base64Key));
        string exported  = Convert.ToBase64String(key.Export(blobType));
        var    p2        = KeyFormatter.GetFormatter(blobType).Read(Convert.FromBase64String(exported));

        this.LogRSAParameterComparison("Original", p1, "Re-exported", p2);
        if (blobType == CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo && exported.Length == base64Key.Length - 20)
        {
            // I'm not sure what the last 20 bytes are (perhaps the optional attributes)
            // But Windows platforms produces them and Android doesn't seem to.
            // Since the private key material seems to be elsewhere, we'll exclude
            // the suffix from the comparison.
            // The prefix is also mismatched, but that seems to also be ignorable.
            Assert.Equal(base64Key.Substring(6, exported.Length - 6), exported.Substring(6));
        }
        else
        {
            // This check tends to be too brittle to implementation details of the native crypto,
            // which may re-encode the D parameter for reasons I don't understand.
            ////Assert.Equal(base64Key, exported);

            // The two prime numbers are really all that matter.
            Assert.Equal <byte>(p1.P, p2.P);
            Assert.Equal <byte>(p1.Q, p2.Q);
        }
    }
예제 #3
0
        private void KeyFormatters_PrivateKeyRoundTrip(RSAParameters initialValue, CryptographicPrivateKeyBlobType format)
        {
            this.logger.WriteLine("Generated RSA parameters:");
            this.LogRSAParameters(initialValue, "  ");

            var formatter = KeyFormatter.GetFormatter(format);

            byte[] custom            = formatter.Write(initialValue);
            var    rsaParametersRead = formatter.Read(custom);

            this.logger.WriteLine("Read RSA parameters:");
            this.LogRSAParameters(rsaParametersRead, "  ");

            Assert.Equal <byte>(initialValue.Exponent, rsaParametersRead.Exponent);
            Assert.Equal <byte>(initialValue.Modulus, rsaParametersRead.Modulus);

            Assert.Equal <byte>(initialValue.P, rsaParametersRead.P);
            Assert.Equal <byte>(initialValue.Q, rsaParametersRead.Q);

            if (format != CryptographicPrivateKeyBlobType.BCryptPrivateKey)
            {
                Assert.Equal <byte>(initialValue.D, rsaParametersRead.D);
                Assert.Equal <byte>(initialValue.DP, rsaParametersRead.DP);
                Assert.Equal <byte>(initialValue.DQ, rsaParametersRead.DQ);
                Assert.Equal <byte>(initialValue.InverseQ, rsaParametersRead.InverseQ);
            }
            else
            {
                // BCryptPrivateKey is lossy, by design.
                Assert.Null(rsaParametersRead.D);
                Assert.Null(rsaParametersRead.DP);
                Assert.Null(rsaParametersRead.DQ);
                Assert.Null(rsaParametersRead.InverseQ);
            }
        }
예제 #4
0
        /// <inheritdoc/>
        public ICryptographicKey ImportPublicKey(byte[] keyBlob, CryptographicPublicKeyBlobType blobType = CryptographicPublicKeyBlobType.X509SubjectPublicKeyInfo)
        {
            Requires.NotNull(keyBlob, "keyBlob");

            RSAParameters parameters = KeyFormatter.GetFormatter(blobType).Read(keyBlob);

            // Inject the PKCS#1 public key into the KeyChain.
            string keyIdentifier       = Guid.NewGuid().ToString();
            string publicKeyIdentifier = RsaCryptographicKey.GetPublicKeyIdentifierWithTag(keyIdentifier);
            var    keyQueryDictionary  = RsaCryptographicKey.CreateKeyQueryDictionary(publicKeyIdentifier);

            keyQueryDictionary[KSec.ValueData]    = NSData.FromArray(KeyFormatter.Pkcs1.Write(parameters, includePrivateKey: false));
            keyQueryDictionary[KSec.AttrKeyClass] = KSec.AttrKeyClassPublic;
            keyQueryDictionary[KSec.ReturnRef]    = NSNumber.FromBoolean(true);
            IntPtr resultHandle;
            int    status = RsaCryptographicKey.SecItemAdd(keyQueryDictionary.Handle, out resultHandle);

            if (resultHandle != IntPtr.Zero)
            {
                var key = new SecKey(resultHandle, true);
                return(new RsaCryptographicKey(key, keyIdentifier, this.Algorithm));
            }
            else
            {
                throw new InvalidOperationException("SecItemAdd return " + status);
            }
        }
예제 #5
0
        public void SanitizeKeyTests(string oldKey, string newKey)
        {
            // Act
            var result = KeyFormatter.SanitizeKey(oldKey);

            // Assert
            result.Should().Be(newKey);
        }
        /// <inheritdoc/>
        public ICryptographicKey ImportPublicKey(byte[] keyBlob, CryptographicPublicKeyBlobType blobType = CryptographicPublicKeyBlobType.X509SubjectPublicKeyInfo)
        {
            Requires.NotNull(keyBlob, "keyBlob");

            var rsa = new Platform.RSACryptoServiceProvider();

            rsa.ImportParameters(KeyFormatter.ToPlatformParameters(KeyFormatter.GetFormatter(blobType).Read(keyBlob)));
            return(new RsaCryptographicKey(rsa, this.algorithm));
        }
예제 #7
0
        /// <summary>
        /// Creates a cryptographic key based on the specified RSA parameters.
        /// </summary>
        /// <param name="provider">The asymmetric algorithm provider.</param>
        /// <param name="parameters">The RSA parameters from which to initialize the key.</param>
        /// <returns>The cryptographic key.</returns>
        public static ICryptographicKey ImportParameters(this IAsymmetricKeyAlgorithmProvider provider, RSAParameters parameters)
        {
            Requires.NotNull(provider, nameof(provider));

            byte[] keyBlob = KeyFormatter.Pkcs1.Write(parameters);
            return(KeyFormatter.HasPrivateKey(parameters)
                ? provider.ImportKeyPair(keyBlob, CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey)
                : provider.ImportPublicKey(keyBlob, CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey));
        }
예제 #8
0
파일: Ext.cs 프로젝트: dlech/SshAgentLib
   public static ISshKey AddKeyFromFile(this IAgent agent, string fileName,
 ICollection<Agent.KeyConstraint> constraints,
 KeyFormatter.GetPassphraseCallback getPassword = null)
   {
       if (getPassword == null) {
       getPassword = PasswordCallbackFactory(
         string.Format(Strings.msgEnterPassphrase, Path.GetFileName(fileName)));
         }
         return agent.AddKeyFromFile(fileName, getPassword, constraints);
   }
예제 #9
0
        public LazyMemoryCache(string name, ValueFactory valueFactory, PolicyProvider policyProvider = null, KeyFormatter keyFormatter = null,
                               ValueRemoved valueRemoved = null)
        {
            _valueFactory   = valueFactory;
            _policyProvider = policyProvider ?? DefaultPolicyProvider;
            _keyFormatter   = keyFormatter ?? DefaultKeyFormatter;
            _valueRemoved   = valueRemoved ?? DefaultValueRemoved;

            _cache = new MemoryCache(name);
        }
예제 #10
0
        public void Test()
        {
            var formatter = new KeyFormatter();

            Assert.Throws <ArgumentNullException>(() => formatter.Format <string?>(null));

            var key = Guid.NewGuid();

            Assert.Equal(key.ToString(), formatter.Format(key.ToString()));
            Assert.Equal(key.ToString(), formatter.Format(key));
        }
예제 #11
0
        public LazyMemoryCache(string name, ValueFactory valueFactory, PolicyProvider policyProvider = null, KeyFormatter keyFormatter = null,
                               ValueRemoved valueRemoved = null)
        {
            _valueFactory   = valueFactory;
            _policyProvider = policyProvider ?? DefaultPolicyProvider;
            _keyFormatter   = keyFormatter ?? DefaultKeyFormatter;
            _valueRemoved   = valueRemoved ?? DefaultValueRemoved;

            _cache     = new MemoryCache(name);
            _scheduler = new LimitedConcurrencyLevelTaskScheduler(1);
        }
        /// <inheritdoc/>
        public ICryptographicKey ImportPublicKey(byte[] keyBlob, CryptographicPublicKeyBlobType blobType = CryptographicPublicKeyBlobType.X509SubjectPublicKeyInfo)
        {
            Requires.NotNull(keyBlob, "keyBlob");

            var        parameters = KeyFormatter.GetFormatter(blobType).Read(keyBlob);
            var        spec       = new RSAPublicKeySpec(new BigInteger(1, parameters.Modulus), new BigInteger(1, parameters.Exponent));
            KeyFactory factory    = KeyFactory.GetInstance("RSA");
            IPublicKey publicKey  = factory.GeneratePublic(spec);

            return(new RsaCryptographicKey(publicKey, parameters, this.algorithm));
        }
예제 #13
0
 /// <inheritdoc />
 public byte[] Export(CryptographicPrivateKeyBlobType blobType)
 {
     try
     {
         return(KeyFormatter.GetFormatter(blobType).Write(KeyFormatter.ToPCLParameters(this.key.ExportParameters(true))));
     }
     catch (CryptographicException ex)
     {
         throw new InvalidOperationException("Private key not available.", ex);
     }
 }
예제 #14
0
        /// <inheritdoc/>
        public ICryptographicKey ImportKeyPair(byte[] keyBlob, CryptographicPrivateKeyBlobType blobType = CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo)
        {
            Requires.NotNull(keyBlob, "keyBlob");

            RSAParameters parameters = KeyFormatter.GetFormatter(blobType).Read(keyBlob);

            string keyIdentifier = Guid.NewGuid().ToString();
            SecKey privateKey    = ImportKey(parameters, RsaCryptographicKey.GetPrivateKeyIdentifierWithTag(keyIdentifier));
            SecKey publicKey     = ImportKey(KeyFormatter.PublicKeyFilter(parameters), RsaCryptographicKey.GetPublicKeyIdentifierWithTag(keyIdentifier));

            return(new RsaCryptographicKey(publicKey, privateKey, keyIdentifier, this.Algorithm));
        }
예제 #15
0
        /// <summary>Creates a cryptographic key based on the specified RSA parameters.</summary>
        /// <param name="provider">The asymmetric algorithm provider.</param>
        /// <param name="parameters">The RSA parameters from which to initialize the key.</param>
        /// <returns>The cryptographic key.</returns>
        public static ICryptographicKey ImportParameters(this IAsymmetricKeyAlgorithmProvider provider, RSAParameters parameters)
        {
#if PCL
            throw new NotImplementedException("Not implemented in reference assembly.");
#else
            Requires.NotNull(provider, "provider");

            byte[] keyBlob = KeyFormatter.Pkcs1.Write(parameters);
            return(KeyFormatter.HasPrivateKey(parameters)
                ? provider.ImportKeyPair(keyBlob, CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey)
                : provider.ImportPublicKey(keyBlob, CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey));
#endif
        }
        /// <inheritdoc/>
        public ICryptographicKey ImportPublicKey(byte[] keyBlob, CryptographicPublicKeyBlobType blobType)
        {
            Requires.NotNull(keyBlob, "keyBlob");

            using (var provider = NCryptOpenStorageProvider(KeyStorageProviders.MS_KEY_STORAGE_PROVIDER))
            {
                byte[] bcryptPublicBlob = blobType == this.NativePublicKeyFormatEnum
            ? keyBlob
            : KeyFormatter.GetFormatter(this.NativePublicKeyFormatEnum).Write(KeyFormatter.GetFormatter(blobType).Read(keyBlob));
                var key = NCryptImportKey(provider, null, this.NativePublicKeyFormatString, IntPtr.Zero, bcryptPublicBlob);
                return(this.CreateKey(key, isPublicOnly: true));
            }
        }
예제 #17
0
        public static string Serialize(InfluxPoint point)
        {
            var tags   = point.Tags;
            var fields = point.Fields;

            var allTags   = string.Join(",", TagsFormatter.Format(tags));
            var allFields = string.Join(",", FieldFormatter.Format(fields));

            var tagsPart = allTags.Length > 0 ? $",{allTags}" : allTags;

            var measurement = KeyFormatter.Format(point.Measurement);

            return($"{measurement}{tagsPart} {allFields} {FieldValueFormatter.FormatTimestamp(point.UtcTimestamp)}".Trim());
        }
예제 #18
0
 static KeyFormatterTests()
 {
     rsaParameters = new Lazy <RSAParameters>(() =>
     {
         var algorithm = WinRTCrypto.AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithm.RsaOaepSha1);
         using (var key = algorithm.CreateKeyPair(512))
         {
             const CryptographicPrivateKeyBlobType keyBlobFormat = CryptographicPrivateKeyBlobType.BCryptFullPrivateKey;
             byte[] bcryptNative = key.Export(keyBlobFormat);
             var rsaParameters   = KeyFormatter.GetFormatter(keyBlobFormat).Read(bcryptNative);
             return(rsaParameters);
         }
     });
 }
예제 #19
0
        public RepositoryConfiguration(
            string repositoryOwner,
            string repositoryName,
            string hashTags)
        {
            PartitionKey = KeyFormatter.SanitizeKey(Configuration.RepositoryConfigurations.PartitionKey);
            RowKey       = KeyFormatter.SanitizeKey($"{repositoryOwner}|{repositoryName}");

            RepositoryOwner = repositoryOwner;
            RepositoryName  = repositoryName;
            HashTags        = hashTags;
            CreatedAt       = DateTime.UtcNow;
            IsActive        = true;
        }
        /// <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;
            }
        }
예제 #21
0
        public PublicationConfiguration(
            string publicationSourceOwner,
            string publicationSourceName,
            string publicationUrl,
            string hashTags)
        {
            PartitionKey = KeyFormatter.SanitizeKey(Configuration.PublicationConfigurations.PartitionKey);
            RowKey       = KeyFormatter.SanitizeKey($"{publicationSourceOwner}|{publicationSourceName}");

            PublicationSourceOwner = publicationSourceOwner;
            PublicationSourceName  = publicationSourceName;
            PublicationSourceUrl   = publicationUrl;
            HashTags = hashTags;
            IsActive = true;
        }
예제 #22
0
 public IEnumerator <KeyValuePair <TKey, TValue> > GetEnumerator()
 {
     for (int i = 0; i < Count; i++)
     {
         TKey key = KeyFormatter.Deserialize(ref _reader, ref _context);
         if (IsOnlyReadFieldOffset)
         {
             BssomFieldOffsetInfo offset = new BssomFieldOffsetInfo(_reader.Position);
             yield return(new KeyValuePair <TKey, TValue>(key, Unsafe.As <BssomFieldOffsetInfo, TValue>(ref offset)));
         }
         else
         {
             yield return(new KeyValuePair <TKey, TValue>(key, ValueFormatter.Deserialize(ref _reader, ref _context)));
         }
     }
 }
예제 #23
0
        /// <inheritdoc />
        public override byte[] Export(CryptographicPrivateKeyBlobType blobType = CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo)
        {
            Verify.Operation(!this.IsPublicOnly, "Only public key is available.");
            try
            {
                byte[] nativeBlob;
                string nativeFormatString;
                CryptographicPrivateKeyBlobType nativeBlobType;
                if (this.Provider.NativePrivateKeyFormats.TryGetValue(blobType, out nativeFormatString))
                {
                    nativeBlobType = blobType;
                }
                else
                {
                    nativeBlobType     = this.Provider.PreferredNativePrivateKeyFormat;
                    nativeFormatString = this.Provider.NativePrivateKeyFormats[nativeBlobType];
                }

#if NET40
                nativeBlob = NCryptExportKey(this.Key, SafeKeyHandle.Null, nativeFormatString, IntPtr.Zero).ToByteArray();
#else
                nativeBlob = NCryptExportKey(this.Key, SafeKeyHandle.Null, nativeFormatString, IntPtr.Zero).ToArray();
#endif

                byte[] formattedBlob;
                if (nativeBlobType != blobType)
                {
                    var parameters = KeyFormatter.GetFormatter(nativeBlobType).Read(nativeBlob);
                    formattedBlob = KeyFormatter.GetFormatter(blobType).Write(parameters);
                }
                else
                {
                    formattedBlob = nativeBlob;
                }

                return(formattedBlob);
            }
            catch (SecurityStatusException ex)
            {
                if (ex.NativeErrorCode == SECURITY_STATUS.NTE_NOT_SUPPORTED)
                {
                    throw new NotSupportedException(ex.Message, ex);
                }

                throw;
            }
        }
예제 #24
0
        public void KeyFormatters_PublicKeyRoundTrip(CryptographicPublicKeyBlobType format)
        {
            var formatter = KeyFormatter.GetFormatter(format);

            byte[] custom            = formatter.Write(rsaParameters.Value, includePrivateKey: false);
            var    rsaParametersRead = formatter.Read(custom);

            Assert.Equal <byte>(rsaParameters.Value.Exponent, rsaParametersRead.Exponent);
            Assert.Equal <byte>(rsaParameters.Value.Modulus, rsaParametersRead.Modulus);

            Assert.Null(rsaParametersRead.D);
            Assert.Null(rsaParametersRead.P);
            Assert.Null(rsaParametersRead.Q);
            Assert.Null(rsaParametersRead.DP);
            Assert.Null(rsaParametersRead.DQ);
            Assert.Null(rsaParametersRead.InverseQ);
        }
예제 #25
0
 public Publication(
     string publicationSourceName,
     string id,
     DateTimeOffset publicationDate,
     string title,
     string description,
     string url,
     string hashTags)
 {
     PartitionKey          = KeyFormatter.SanitizeKey(publicationSourceName);
     PublicationSourceName = publicationSourceName;
     RowKey          = KeyFormatter.SanitizeKey($"{id}-{publicationDate.ToUnixTimeSeconds()}");
     Id              = id;
     PublicationDate = publicationDate;
     Title           = title;
     Description     = description;
     Url             = url;
     HashTags        = hashTags;
 }
예제 #26
0
        /// <inheritdoc />
        public override byte[] ExportPublicKey(CryptographicPublicKeyBlobType blobType)
        {
            try
            {
                byte[] nativeBlob    = NCryptExportKey(this.Key, SafeKeyHandle.Null, this.Provider.NativePublicKeyFormatString, IntPtr.Zero).ToArray();
                byte[] formattedBlob = blobType == this.Provider.NativePublicKeyFormatEnum
                    ? nativeBlob
                    : KeyFormatter.GetFormatter(blobType).Write(KeyFormatter.GetFormatter(this.Provider.NativePublicKeyFormatEnum).Read(nativeBlob));
                return(formattedBlob);
            }
            catch (SecurityStatusException ex)
            {
                if (ex.NativeErrorCode == SECURITY_STATUS.NTE_NOT_SUPPORTED)
                {
                    throw new NotSupportedException(ex.Message, ex);
                }

                throw;
            }
        }
        /// <inheritdoc/>
        public ICryptographicKey ImportKeyPair(byte[] keyBlob, CryptographicPrivateKeyBlobType blobType = CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo)
        {
            Requires.NotNull(keyBlob, "keyBlob");

            RSAParameters parameters = KeyFormatter.GetFormatter(blobType).Read(keyBlob);
            IPrivateKey   privateKey;
            IPublicKey    publicKey;

            var spec    = new RSAPrivateKeySpec(new BigInteger(1, parameters.Modulus), new BigInteger(1, parameters.D));
            var factory = KeyFactory.GetInstance("RSA");

            privateKey = factory.GeneratePrivate(spec);

            var privateRsaKey = privateKey.JavaCast <IRSAPrivateKey>();
            var publicKeySpec = new RSAPublicKeySpec(privateRsaKey.Modulus, new BigInteger(1, parameters.Exponent));

            publicKey = factory.GeneratePublic(publicKeySpec);

            return(new RsaCryptographicKey(publicKey, privateKey, parameters, this.algorithm));
        }
예제 #28
0
        /// <inheritdoc />
        public byte[] Export(CryptographicPrivateKeyBlobType blobType)
        {
            NSData data = KeyDataWithTag(GetPrivateKeyIdentifierWithTag(this.keyIdentifier));

            Verify.Operation(data != null, "Private key not available.");
            byte[] keyData;
            try
            {
                keyData = data.ToArray();
            }
            catch (ArgumentNullException ex)
            {
                // MonoTouch throws this when the private key is missing.
                throw new InvalidOperationException("Private key not available.", ex);
            }

            var parameters = KeyFormatter.Pkcs1.Read(keyData);

            return(KeyFormatter.GetFormatter(blobType).Write(parameters));
        }
예제 #29
0
        static ISshKey GetSshKey(Func <Stream> getPrivateKeyStream,
                                 Func <Stream> getPublicKeyStream,
                                 string fallbackComment,
                                 KeyFormatter.GetPassphraseCallback getPassphrase)
        {
            ISshKey key;

            using (var privateKeyStream = getPrivateKeyStream())
                key = privateKeyStream.ReadSshKey(getPassphrase);
            if (string.IsNullOrWhiteSpace(key.Comment) && getPublicKeyStream != null)
            {
                using (var stream = getPublicKeyStream())
                    key.Comment = KeyFormatter.GetComment(stream.ReadAllLines(Encoding.UTF8));
            }
            if (string.IsNullOrWhiteSpace(key.Comment))
            {
                key.Comment = fallbackComment;
            }
            return(key);
        }
        /// <inheritdoc/>
        public ICryptographicKey ImportKeyPair(byte[] keyBlob, CryptographicPrivateKeyBlobType blobType = CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo)
        {
            Requires.NotNull(keyBlob, "keyBlob");

            var parameters = KeyFormatter.GetFormatter(blobType)
                             .Read(keyBlob)
                             .ComputeFullPrivateKeyData();

            if (!CapiKeyFormatter.IsCapiCompatible(parameters))
            {
                // Try to make it CAPI compatible since it's faster on desktop,
                // and the only thing that could possibly work on wp8.
                RSAParameters adjustedParameters = KeyFormatter.NegotiateSizes(parameters);
                if (CapiKeyFormatter.IsCapiCompatible(adjustedParameters))
                {
                    parameters = adjustedParameters;
                }
            }

            Platform.RSA rsa;
            if (CapiKeyFormatter.IsCapiCompatible(parameters))
            {
                rsa = new Platform.RSACryptoServiceProvider();
            }
            else
            {
#if DESKTOP
                rsa = new RSAManaged();
#else
                // Throw the exception explaining the problem.
                CapiKeyFormatter.VerifyCapiCompatibleParameters(parameters);

                // Make it obvious to the compiler that the buck stops here.
                // er... on the line above.
                throw new NotSupportedException();
#endif
            }

            rsa.ImportParameters(KeyFormatter.ToPlatformParameters(parameters));
            return(new RsaCryptographicKey(rsa, this.algorithm));
        }
예제 #31
0
    public void Pkcs1DecodingTest()
    {
#pragma warning disable 0436
        // Initialize the "Known Good" RSAParameters.
        byte[] capi1Blob = Convert.FromBase64String(AsymmetricKeyAlgorithmProviderTests.Helper.PrivateKeyFormatsAndBlobs[Tuple.Create(PCLCrypto.AsymmetricAlgorithm.RsaOaepSha1, CryptographicPrivateKeyBlobType.Capi1PrivateKey)]);
        var    rsa       = new RSACryptoServiceProvider();
        rsa.ImportCspBlob(capi1Blob);
        RSAParameters rsaCapi = rsa.ExportParameters(true);

        // Now load up the tested one.
        byte[]        pkcs1KeyBlob  = Convert.FromBase64String(AsymmetricKeyAlgorithmProviderTests.Helper.PrivateKeyFormatsAndBlobs[Tuple.Create(PCLCrypto.AsymmetricAlgorithm.RsaOaepSha1, CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey)]);
        RSAParameters homeReadPkcs1 = KeyFormatter.ToPlatformParameters(KeyFormatter.Pkcs1.Read(pkcs1KeyBlob));
#pragma warning restore 0436
        Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.Modulus), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.Modulus));
        Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.Exponent), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.Exponent));
        Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.D), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.D));
        Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.P), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.P));
        Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.Q), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.Q));
        Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.DP), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.DP));
        Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.DQ), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.DQ));
        Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.InverseQ), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.InverseQ));
    }