Example #1
0
        public static Task <RSAAsymmetricKey> GetCryptoKeyAsync(CancellationToken cancelToken = default(CancellationToken))
        {
            return(Task.Run(() => {
                RSAAsymmetricKey key = null;
                if (KeyFile.Exists)
                {
                    try {
                        using (var stream = File.OpenRead(KeyFile.FullName)) {
                            var reader = new StreamValueReader(stream);
                            RSAParameters parameters = RSAParametersSerializer.Deserialize(reader);
                            key = new RSAAsymmetricKey(parameters);
                        }
                    } catch (Exception ex) {
                        Trace.TraceWarning("Failed to read key: {0}", ex);
                        KeyFile.Delete();
                    }
                }

                cancelToken.ThrowIfCancellationRequested();

                if (!KeyFile.Exists)
                {
                    var rsa = new RSACrypto();
                    RSAParameters parameters = rsa.ExportKey(true);
                    key = new RSAAsymmetricKey(parameters);

                    cancelToken.ThrowIfCancellationRequested();

                    using (var stream = File.OpenWrite(KeyFile.FullName)) {
                        var writer = new StreamValueWriter(stream);
                        RSAParametersSerializer.Serialize(writer, parameters);
                    }
                }

                return key;
            }, cancelToken));
        }