Example #1
0
        /// <summary>
        /// Decrypts and verifies the data.
        /// </summary>
        /// <param name="cipherData">The cipher data.</param>
        /// <param name="privateKey">The Private key to decrypt.</param>
        /// <param name="publicKeys"> The list of trusted public keys for verification,
        /// which can contain signer's public key.</param>
        /// <returns>The decrypted data</returns>
        /// <exception cref="Virgil.SDK.Exceptions.SignatureIsNotValidException"></exception>
        /// <exception cref="Virgil.SDK.Exceptions.CryptoException"></exception>
        /// <example>
        ///     <code>
        ///         var crypto = new VirgilCrypto();
        ///         var decryptedData = crypto.DecryptThenVerify(cipherData, bob.PrivateKey, alice.PublicKey);
        ///     </code>
        /// </example>
        /// How to get cipherData as well as Alice's and Bob's key pairs.
        /// <see cref="SignThenEncrypt(byte[] data, IPrivateKey privateKey, params IPublicKey[] recipients)"/>
        public override byte[] DecryptThenVerify(byte[] cipherData, IPrivateKey privateKey, params IPublicKey[] publicKeys)
        {
            try
            {
                using (var signer = new VirgilSigner())
                    using (var cipher = new VirgilCipher())
                    {
                        var decryptedData = cipher.DecryptWithKey(cipherData, privateKey.Get().ReceiverId, privateKey.Get().Value);
                        var signature     = cipher.CustomParams().GetData(this.CustomParamKeySignature);

                        var signerPublicKey = publicKeys.FirstOrDefault();
                        if (publicKeys.Length > 1)
                        {
                            var signerId = cipher.CustomParams().GetData(this.CustomParamKeySignerId);
                            signerPublicKey = publicKeys.Single(publicKey => publicKey.Get().ReceiverId.SequenceEqual(signerId));
                        }

                        var isValid = signer.Verify(decryptedData, signature, signerPublicKey.Get().Value);
                        if (!isValid)
                        {
                            throw new SignatureIsNotValidException();
                        }

                        return(decryptedData);
                    }
            }
            catch (Exception ex)
            {
                throw new CryptoException(ex.Message);
            }
        }
Example #2
0
        /**
         * @TODO this should extend file system based tests and resolve tests via autofac container
         */
        public DeltaExecutorTests()
        {
            _specProvider  = new CatalystSpecProvider();
            _stateProvider = new StateProvider(new StateDb(), new StateDb(), LimboLogs.Instance);
            var  storageProvider = new StorageProvider(new StateDb(), _stateProvider, LimboLogs.Instance);
            IKvm virtualMachine  = new KatVirtualMachine(_stateProvider, storageProvider, new StateUpdateHashProvider(),
                                                         _specProvider, LimboLogs.Instance);
            var logger = Substitute.For <ILogger>();

            logger.IsEnabled(Arg.Any <LogEventLevel>()).Returns(true);

            _senderPrivateKey = _cryptoContext.GeneratePrivateKey();
            _senderPublicKey  = _senderPrivateKey.GetPublicKey();

            _recipient  = _cryptoContext.GeneratePrivateKey().GetPublicKey();
            _poorSender = _cryptoContext.GeneratePrivateKey().GetPublicKey();

            _stateProvider.CreateAccount(_poorSender.ToKvmAddress(), 0.Kat());
            _stateProvider.CreateAccount(_senderPublicKey.ToKvmAddress(), 1000.Kat());
            _stateProvider.CreateAccount(Address.Zero, 1000.Kat());
            _stateProvider.Commit(_specProvider.GenesisSpec);

            _executor = new DeltaExecutor(_specProvider, _stateProvider, storageProvider, virtualMachine,
                                          new FfiWrapper(), logger);

            _signingContext = new SigningContext
            {
                NetworkType   = NetworkType.Devnet,
                SignatureType = SignatureType.TransactionPublic
            };
        }
Example #3
0
        /// <summary>
        /// Decrypts and verifies the specified data.
        /// </summary>
        /// <param name="cipherData">The cipher data.</param>
        /// <param name="privateKey">The Private key to decrypt.</param>
        /// <param name="publicKeys"> The list of trusted public keys for verification,
        /// which can contain signer's public key.</param>
        /// <returns>The decrypted and verified data</returns>
        /// <exception cref="VirgilCryptoException"></exception>
        /// <example>
        ///     <code>
        ///         var crypto = new VirgilCrypto();
        ///         var decryptedData = crypto.DecryptThenVerify(cipherData, bob.PrivateKey, alice.PublicKey);
        ///     </code>
        /// </example>
        /// <remarks>How to get cipherData as well as Alice's and Bob's key pairs
        /// <see cref="SignThenEncrypt(byte[], IPrivateKey, IPublicKey[])"/>.</remarks>
        public byte[] DecryptThenVerify(byte[] cipherData, IPrivateKey privateKey, params IPublicKey[] publicKeys)
        {
            try
            {
                using (VirgilSigner signer = new VirgilSigner(VirgilHash.Algorithm.SHA512))
                    using (VirgilCipher cipher = new VirgilCipher())
                    {
                        byte[] decryptedData =
                            cipher.DecryptWithKey(cipherData, VirgilCryptoExtentions.Get(privateKey).Id,
                                                  VirgilCryptoExtentions.Get(privateKey).RawKey);
                        byte[] signature = cipher.CustomParams().GetData(this.CustomParamKeySignature);

                        IPublicKey signerPublicKey = (publicKeys.Length > 0) ? publicKeys[0] : null;
                        if (publicKeys.Length > 1)
                        {
                            byte[] signerId = cipher.CustomParams().GetData(this.CustomParamKeySignerId);
                            signerPublicKey = FindPublicKeyBySignerId(publicKeys, signerId);
                        }

                        bool isValid = signer.Verify(decryptedData, signature, VirgilCryptoExtentions.Get(signerPublicKey).RawKey);
                        if (!isValid)
                        {
                            throw new VirgilCryptoException("Signature is not valid.");
                        }

                        return(decryptedData);
                    }
            }
            catch (Exception ex)
            {
                throw new VirgilCryptoException(ex.Message);
            }
        }
Example #4
0
        /// <summary>
        /// Signs the specified data using the specified Private key.
        /// </summary>
        /// <param name="data">raw data bytes for signing.</param>
        /// <param name="privateKey">private key for signing.</param>
        /// <returns>Signature data.</returns>
        /// <example>
        ///     <code>
        ///         var crypto = new VirgilCrypto();
        ///         var keyPair = crypto.GenerateKeys();
        ///         var data = Encoding.UTF8.GetBytes("Hello Bob!");
        ///         var signature = crypto.GenerateSignature(data, keyPair.PrivateKey);
        ///     </code>
        /// </example>
        /// <remarks>How to verify signature <see cref="VerifySignature(byte[], byte[], IPublicKey)"/>.</remarks>
        public byte[] GenerateSignature(byte[] data, IPrivateKey privateKey)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (privateKey == null)
            {
                throw new ArgumentNullException("privateKey");
            }

            try
            {
                using (VirgilSigner signer = new VirgilSigner(VirgilHash.Algorithm.SHA512))
                {
                    byte[] signature = signer.Sign(data, VirgilCryptoExtentions.Get(privateKey).RawKey);
                    return(signature);
                }
            }
            catch (Exception ex)
            {
                throw new VirgilCryptoException(ex.Message);
            }
        }
Example #5
0
        /// <summary>
        /// Signs and encrypts the specified data.
        /// </summary>
        /// <param name="data">The data to encrypt.</param>
        /// <param name="privateKey">The Private key to sign the data.</param>
        /// <param name="recipients">The list of Public key recipients to encrypt the data.</param>
        /// <returns>Signed and encrypted data bytes.</returns>
        /// <exception cref="Virgil.Crypto.VirgilCryptoException"></exception>
        /// <example>
        ///   <code>
        ///     var crypto = new VirgilCrypto();
        ///     var alice = crypto.GenerateKeys();
        ///     var bob = crypto.GenerateKeys();
        ///     var originalData = Encoding.UTF8.GetBytes("Hello Bob, How are you?");
        ///     // The data to be signed with Alice's Private key and then encrypted for Bob.
        ///     var cipherData = crypto.SignThenEncrypt(originalData, alice.PrivateKey, bob.PublicKey);
        ///   </code>
        /// </example>
        public byte[] SignThenEncrypt(byte[] data, IPrivateKey privateKey, params IPublicKey[] recipients)
        {
            try
            {
                using (VirgilSigner signer = new VirgilSigner(VirgilHash.Algorithm.SHA512))
                    using (VirgilCipher cipher = new VirgilCipher())
                    {
                        byte[] signature = signer.Sign(data, VirgilCryptoExtentions.Get(privateKey).RawKey);

                        VirgilCustomParams customData = cipher.CustomParams();
                        customData.SetData(this.CustomParamKeySignature, signature);

                        IPublicKey publicKey = this.ExtractPublicKey(privateKey);

                        customData.SetData(this.CustomParamKeySignerId, VirgilCryptoExtentions.Get(publicKey).Id);

                        foreach (IPublicKey recipientPublicKey in recipients)
                        {
                            cipher.AddKeyRecipient(VirgilCryptoExtentions.Get(recipientPublicKey).Id,
                                                   VirgilCryptoExtentions.Get(recipientPublicKey).RawKey);
                        }

                        return(cipher.Encrypt(data, true));
                    }
            }
            catch (Exception ex)
            {
                throw new VirgilCryptoException(ex.Message);
            }
        }
Example #6
0
        /// <summary>
        /// Sign passed request with authority private key.
        /// </summary>
        /// <param name="request">request for signing.</param>
        /// <param name="appId">authority id.</param>
        /// <param name="appKey">authority private key to sign with.</param>
        public void AuthoritySign(ISignableRequest request, string appId, IPrivateKey appKey)
        {
            var fingerprint = this.crypto.CalculateFingerprint(request.Snapshot);
            var signature   = this.crypto.Sign(fingerprint.GetValue(), appKey);

            request.AppendSignature(appId, signature);
        }
Example #7
0
        /// <summary>
        /// Signs the specified data using Private key.
        /// </summary>
        public override byte[] Sign(byte[] data, IPrivateKey privateKey)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            if (privateKey == null)
            {
                throw new ArgumentNullException(nameof(privateKey));
            }

            try
            {
                using (var signer = new VirgilSigner())
                {
                    var signature = signer.Sign(data, privateKey.Get().Value);
                    return(signature);
                }
            }
            catch (Exception ex)
            {
                throw new CryptoException(ex.Message);
            }
        }
Example #8
0
        /// <summary>
        /// Signs and encrypts the data.
        /// </summary>
        /// <param name="data">The data to encrypt.</param>
        /// <param name="privateKey">The Private key to sign the <param name="data"></param>.</param>
        /// <param name="recipients">The list of Public key recipients to encrypt the <param name="data"></param>.</param>
        /// <returns></returns>
        /// <exception cref="Virgil.SDK.Exceptions.CryptoException"></exception>
        public override byte[] SignThenEncrypt(byte[] data, IPrivateKey privateKey, params IPublicKey[] recipients)
        {
            try
            {
                using (var signer = new VirgilSigner())
                    using (var cipher = new VirgilCipher())
                    {
                        var signature = signer.Sign(data, privateKey.Get().Value);

                        var customData = cipher.CustomParams();
                        customData.SetData(this.CustomParamKeySignature, signature);

                        foreach (var publicKey in recipients)
                        {
                            cipher.AddKeyRecipient(publicKey.Get().ReceiverId, publicKey.Get().Value);
                        }

                        return(cipher.Encrypt(data, true));
                    }
            }
            catch (Exception ex)
            {
                throw new CryptoException(ex.Message);
            }
        }
Example #9
0
        /// <summary>
        /// Sign passed request with private key.
        /// </summary>
        /// <param name="request">request for signing.</param>
        /// <param name="privateKey">private key to sign with.</param>
        public void SelfSign(ISignableRequest request, IPrivateKey privateKey)
        {
            var fingerprint = this.crypto.CalculateFingerprint(request.Snapshot);
            var signature   = this.crypto.Sign(fingerprint.GetValue(), privateKey);

            request.AppendSignature(fingerprint.ToHEX(), signature);
        }
        public void PrivateKey_Can_Be_Created_With_Valid_Input()
        {
            var         privateKeyBytes = GenerateRandomByteArray(_wrapper.PrivateKeyLength);
            IPrivateKey privateKey      = _wrapper.GetPrivateKeyFromBytes(privateKeyBytes);

            privateKey.Should().NotBe(null);
        }
        public async Task UpdateKeyProtectorAsync(IPrivateKey currentKeyProtector, IPublicKey newKeyProtector)
        {
            if (currentKeyProtector == null)
            {
                throw new ArgumentNullException("currentKeyProtector");
            }
            if (currentKeyProtector.KeyId != _encryptedKey.KeyId)
            {
                throw new ArgumentException(string.Format("currentKeyProtector.KeyId '{0}' does not match encryptedKey.KeyId '{1}'.", currentKeyProtector.KeyId, _encryptedKey.KeyId));
            }
            if (newKeyProtector == null)
            {
                throw new ArgumentNullException("newKeyProtector");
            }

            // decrypt the key and populate to the x509
            var asymEnc   = new AsymmetricEncryptor();
            var decrypted = await asymEnc.DecryptObjectAsync(_encryptedKey, currentKeyProtector);

            var pfxBytes = decrypted as byte[];

            if (pfxBytes == null || !pfxBytes.Any())
            {
                throw new CryptographicException(string.Format("encryptedKey successfull decrypted but was not a valid PFX byte array. Type was '{0}'.", decrypted.GetType().FullName));
            }
            // re-encrypt the key
            var newAsymEncObj = await asymEnc.EncryptObjectAsync(pfxBytes, newKeyProtector);

            _encryptedKey = newAsymEncObj;
        }
        public async Task UpdateKeyProtectorAsync(IPrivateKey currentKeyProtector, IPublicKey newKeyProtector)
        {
            if (currentKeyProtector == null)
            {
                throw new ArgumentNullException("currentKeyProtector");
            }
            if (currentKeyProtector.KeyId != _encryptedKey.KeyId)
            {
                throw new ArgumentException(string.Format("currentKeyProtector.KeyId '{0}' does not match encryptedKey.KeyId '{1}'.", currentKeyProtector.KeyId, _encryptedKey.KeyId));
            }
            if (newKeyProtector == null)
            {
                throw new ArgumentNullException("newKeyProtector");
            }

            // decrypt the key and populate to the x509
            var asymEnc = new AsymmetricEncryptor();
            var decrypted = await asymEnc.DecryptObjectAsync(_encryptedKey, currentKeyProtector);
            var pfxBytes = decrypted as byte[];
            if (pfxBytes == null || !pfxBytes.Any())
            {
                throw new CryptographicException(string.Format("encryptedKey successfull decrypted but was not a valid PFX byte array. Type was '{0}'.", decrypted.GetType().FullName));
            }
            // re-encrypt the key
            var newAsymEncObj = await asymEnc.EncryptObjectAsync(pfxBytes, newKeyProtector);
            _encryptedKey = newAsymEncObj;
        }
Example #13
0
 internal ChoicesSign(int cipherSuite, byte[][] chain,
                      int hashAlgo, IPrivateKey skey)
     : base(cipherSuite, chain)
 {
     this.hashAlgo = hashAlgo;
     this.skey     = skey;
 }
Example #14
0
 public static Signature GenerateSignature(this PublicEntry publicEntry,
                                           ICryptoContext cryptoContext,
                                           IPrivateKey privateKey,
                                           SigningContext context)
 {
     return(GeneratePublicEntrySignature(publicEntry.Clone(), cryptoContext, privateKey, context));
 }
Example #15
0
        public async Task KeyStoreEncryptAsync(IPrivateKey privateKey,
                                               NetworkType networkType,
                                               KeyRegistryTypes keyIdentifier)
        {
            try
            {
                var publicKeyHash = _hashProvider.ComputeMultiHash(privateKey.GetPublicKey().Bytes).ToArray()
                                    .ToByteString();
                var address = new Address
                {
                    PublicKeyHash = publicKeyHash,
                    AccountType   = AccountType.PublicAccount,
                    NetworkType   = networkType
                };

                var securePassword = _passwordManager.RetrieveOrPromptPassword(_defaultNodePassword,
                                                                               "Please create a password for this node");

                var password = StringFromSecureString(securePassword);

                var json = EncryptAndGenerateDefaultKeyStoreAsJson(
                    password,
                    _cryptoContext.ExportPrivateKey(privateKey),
                    address.RawBytes.ToBase32());

                _passwordManager.AddPasswordToRegistry(_defaultNodePassword, securePassword);

                await _fileSystem.WriteTextFileToCddSubDirectoryAsync(keyIdentifier.Name, Constants.KeyStoreDataSubDir,
                                                                      json);
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
            }
        }
Example #16
0
        public static TransactionBroadcast Sign(this TransactionBroadcast transaction,
                                                ICryptoContext cryptoContext,
                                                IPrivateKey privateKey,
                                                SigningContext context)
        {
            var clone = transaction.Clone();

            if (transaction.Signature?.RawBytes.Length == cryptoContext.SignatureLength)
            {
                Logger.Debug("The transaction was already signed, returning a clone.");
                return(clone);
            }

            clone.Signature = null;
            var signatureBytes = cryptoContext.Sign(privateKey, clone.ToByteArray(),
                                                    context.ToByteArray()).SignatureBytes;

            clone.Signature = new Signature
            {
                RawBytes       = signatureBytes.ToByteString(),
                SigningContext = context
            };

            return(clone);
        }
        public void TestGetPublicKeyFromPrivate()
        {
            IPrivateKey privateKey = _wrapper.GeneratePrivateKey();
            IPublicKey  publicKey  = _wrapper.GetPublicKeyFromPrivateKey(privateKey);

            publicKey.Bytes.Length.Should().Be(_wrapper.PublicKeyLength);
        }
Example #18
0
 public CatalystNodePoa(IKeySigner keySigner,
                        IPeerService peer,
                        IConsensus consensus,
                        IDfs dfs,
                        ILedger ledger,
                        ILogger logger,
                        IRpcServer rpcServer,
                        IPeerClient peerClient,
                        IPeerSettings peerSettings,
                        IMempool <TransactionBroadcastDao> mempool,
                        IContract contract = null)
 {
     _peer         = peer;
     _peerClient   = peerClient;
     _peerSettings = peerSettings;
     Consensus     = consensus;
     _dfs          = dfs;
     _ledger       = ledger;
     _keySigner    = keySigner;
     _logger       = logger;
     _rpcServer    = rpcServer;
     _mempool      = mempool;
     _contract     = contract;
     _privateKey   = keySigner.KeyStore.KeyStoreDecrypt(KeyRegistryTypes.DefaultKey);
     _publicKey    = keySigner.CryptoContext.GetPublicKey(_privateKey);
 }
        public void TestGenerateDifferentKey()
        {
            IPrivateKey privateKey1 = _wrapper.GeneratePrivateKey();
            IPrivateKey privateKey2 = _wrapper.GeneratePrivateKey();

            privateKey1.Bytes.Should().NotEqual(privateKey2.Bytes);
        }
Example #20
0
        public PoaTestNode(string name,
                           IPrivateKey privateKey,
                           IPeerSettings nodeSettings,
                           IDfsService dfsService,
                           IEnumerable <PeerId> knownPeerIds,
                           IFileSystem parentTestFileSystem)
        {
            Name          = name;
            _nodeSettings = nodeSettings;

            _nodeDirectory = parentTestFileSystem.GetCatalystDataDir();

            _dfsService = dfsService;

            _rpcSettings = RpcSettingsHelper.GetRpcServerSettings(nodeSettings.Port + 100);
            _nodePeerId  = nodeSettings.PeerId;

            _memPool        = new Mempool(new MempoolService(new InMemoryRepository <PublicEntryDao, string>()));
            _peerRepository = new PeerRepository(new InMemoryRepository <Peer, string>());
            var peersInRepo = knownPeerIds.Select(p => new Peer
            {
                PeerId    = p,
                IsPoaNode = true,
                LastSeen  = DateTime.UtcNow
            }).ToList();

            _peerRepository.Add(peersInRepo);

            _deltaByNumber = new DeltaByNumberRepository(new InMemoryRepository <DeltaByNumber, string>());

            _containerProvider = new ContainerProvider(new[]
            {
                Constants.NetworkConfigFile(NetworkType.Devnet),
                Constants.SerilogJsonConfigFile
            }
                                                       .Select(f => Path.Combine(Constants.ConfigSubFolder, f)), parentTestFileSystem, TestContext.CurrentContext);

            RegisterNodeDependencies(_containerProvider.ContainerBuilder,
                                     excludedModules: new List <Type>
            {
                typeof(ApiModule),
                typeof(RpcServerModule)
            }
                                     );
            _containerProvider.ConfigureContainerBuilder(true, true);
            OverrideContainerBuilderRegistrations();

            _scope = _containerProvider.Container.BeginLifetimeScope(Name);
            _node  = _scope.Resolve <ICatalystNode>();

            var keyStore    = _scope.Resolve <IKeyStore>();
            var keyRegistry = _scope.Resolve <IKeyRegistry>();

            keyRegistry.RemoveItemFromRegistry(KeyRegistryTypes.DefaultKey);
            keyRegistry.AddItemToRegistry(KeyRegistryTypes.DefaultKey, privateKey);

            keyStore.KeyStoreEncryptAsync(privateKey, nodeSettings.NetworkType, KeyRegistryTypes.DefaultKey)
            .ConfigureAwait(false).GetAwaiter()
            .GetResult();
        }
Example #21
0
 public KeyPair(IPrivateKey privateKey, string associatePublicKey = null)
 {
     this.privateKey = privateKey;
     if (!associatePublicKey.IsNull())
     {
         Assert.Equal(associatePublicKey, Public.ToString(), "Associate public key doesn't equal with generated public key");
     }
 }
Example #22
0
 private Data Sign(IPrivateKey privateKey, bool isProtectedEntry)
 {
     IsSigned         = true;
     PrivateKey       = privateKey;
     HasPublicKey     = true;
     IsProtectedEntry = isProtectedEntry;
     return(this);
 }
Example #23
0
        public KeySignerTests()
        {
            _keystore      = Substitute.For <IKeyStore>();
            _keyRegistry   = Substitute.For <IKeyRegistry>();
            _signature     = Substitute.For <ISignature>();
            _privateKey    = Substitute.For <IPrivateKey>();
            _cryptoContext = Substitute.For <ICryptoContext>();

            _cryptoContext.Sign(default, default, default).ReturnsForAnyArgs(_signature);
Example #24
0
 /// <summary>
 /// Load RSA key pair from KeyStore
 /// </summary>
 private static void AccessKeyStore()
 {
     if (_keyStore.ContainsAlias(ALIAS))
     {
         IPrivateKey privateKey = (_keyStore.GetEntry(ALIAS, null) as KeyStore.PrivateKeyEntry).PrivateKey;
         IPublicKey  publicKey  = _keyStore.GetCertificate(ALIAS).PublicKey;
         _keyPair = new KeyPair(publicKey, privateKey);
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="RsaCryptographicKey" /> class.
        /// </summary>
        /// <param name="publicKey">The public key.</param>
        /// <param name="privateKey">The private key.</param>
        /// <param name="parameters">The RSA instance, if available.</param>
        /// <param name="algorithm">The algorithm.</param>
        internal RsaCryptographicKey(IPublicKey publicKey, IPrivateKey privateKey, RSAParameters parameters, AsymmetricAlgorithm algorithm)
        {
            Requires.NotNull(publicKey, "publicKey");
            Requires.NotNull(privateKey, "privateKey");

            this.publicKey = publicKey.JavaCast<IRSAPublicKey>();
            this.privateKey = privateKey.JavaCast<IRSAPrivateKey>();
            this.parameters = parameters;
            this.algorithm = algorithm;
        }
Example #26
0
File: Cert.cs Project: mysoun/Hanyu
        public bool CheckPassword(string password)
        {
            using (var file = new FileStream(this.m_key[0], FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var buff = new byte[file.Length];
                file.Read(buff, 0, buff.Length);

                return(IPrivateKey.CheckPassword(buff, password));
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RsaCryptographicKey" /> class.
        /// </summary>
        /// <param name="publicKey">The public key.</param>
        /// <param name="privateKey">The private key.</param>
        /// <param name="parameters">The RSA instance, if available.</param>
        /// <param name="algorithm">The algorithm.</param>
        internal RsaCryptographicKey(IPublicKey publicKey, IPrivateKey privateKey, RSAParameters parameters, AsymmetricAlgorithm algorithm)
        {
            Requires.NotNull(publicKey, nameof(publicKey));
            Requires.NotNull(privateKey, nameof(privateKey));

            this.publicKey  = publicKey.JavaCast <IRSAPublicKey>() !;
            this.privateKey = privateKey.JavaCast <IRSAPrivateKey>() !;
            this.parameters = parameters;
            this.algorithm  = algorithm;
        }
Example #28
0
        public KeySignerTests()
        {
            _keystore      = Substitute.For <IKeyStore>();
            _keyRegistry   = Substitute.For <IKeyRegistry>();
            _signature     = Substitute.For <ISignature>();
            _privateKey    = Substitute.For <IPrivateKey>();
            _cryptoContext = new CryptoContext(_signature);

            _privateKey.Bytes.Returns(ByteUtil.GenerateRandomByteArray(32));

            _keystore.KeyStoreDecrypt(default).ReturnsForAnyArgs(_privateKey);
        public void Signature_Should_Contain_Public_Key_Corresponding_To_Private_Key()
        {
            IPrivateKey privateKey = _wrapper.GeneratePrivateKey();
            IPublicKey  publicKey  = _wrapper.GetPublicKeyFromPrivateKey(privateKey);

            byte[]     message   = Encoding.UTF8.GetBytes("fa la la la");
            byte[]     context   = Encoding.UTF8.GetBytes("context");
            ISignature signature = _wrapper.Sign(privateKey, message, context);

            signature.PublicKeyBytes.Should().Equal(publicKey.Bytes);
        }
        public void TestStdSignVerify()
        {
            IPrivateKey privateKey = _wrapper.GeneratePrivateKey();

            byte[]     message    = Encoding.UTF8.GetBytes("fa la la la");
            byte[]     context    = Encoding.UTF8.GetBytes("context");
            ISignature signature  = _wrapper.Sign(privateKey, message, context);
            bool       isVerified = _wrapper.Verify(signature, message, context);

            isVerified.Should().BeTrue();
        }
        internal static PrivateKey Get(this IPrivateKey privateKey)
        {
            var theKey = privateKey as PrivateKey;

            if (theKey != null)
            {
                return(theKey);
            }

            throw new NotSupportedException();
        }
        /// <summary>
        /// Stores the private key to the given alias.
        /// </summary>
        /// <param name="privateKey">The private key.</param>
        /// <param name="alias">The alias.</param>
        /// <param name="meta">Some additional data.</param>
        /// <exception cref="DuplicateKeyException"></exception>
        public void Store(IPrivateKey privateKey, string alias, IDictionary <string, string> meta = null)
        {
            var keyEntry = new KeyEntry()
            {
                Meta  = meta,
                Name  = alias,
                Value = privateKeyExporter.ExportPrivatekey(privateKey)
            };

            this.keyStorage.Store(keyEntry);
        }
 public static async Task<SecureString> DecryptFromBase64StringAsync(string encryptedValueAsBase64String, IPrivateKey privateKey)
 {
     return await DecryptFromBase64StringAsync(encryptedValueAsBase64String, privateKey, null);
 }
 public object DecryptObject(AsymmetricallyEncryptedObject input, IPrivateKey privateKey1, IPrivateKey privateKey2)
 {
     return AsyncHelper.RunSync(() => this.DecryptObject_PrivateAsync(input, privateKey1, privateKey2));
 }
 public async Task<object> DecryptObjectAsync(AsymmetricallyEncryptedObject input, IPrivateKey privateKey1, IPrivateKey privateKey2)
 {
     return await this.DecryptObject_PrivateAsync(input, privateKey1, privateKey2);
 }
Example #36
0
 /// <summary>
 /// Encrypt an EC private key with a symmetric key.
 /// </summary>
 /// <param name="privateKey">The EC private key to encrypt</param>
 /// <param name="symmetricKey">The symmetric key with which to encrypt the EC key.  Must be at least
 /// 16 bytes.  Any additional bytes will be ignored.</param>
 /// <returns></returns>
 public static byte[] EncryptPrivateKeyWithAesCbc(IPrivateKey privateKey, byte[] symmetricKey) // EcDiffieHelmanCng
 {
     //byte[] ecAccountLogKeyAsBytes = privateKey.Key.Export(CngKeyBlobFormat.EccPrivateBlob);
     //return EncryptAesCbc(ecAccountLogKeyAsBytes, symmetricKey.Take(16).ToArray(), addHmac: true);
     return new byte[0];
 }
        private async Task<object> DecryptObject_PrivateAsync(AsymmetricallyEncryptedObject input, IPrivateKey privateKey1, IPrivateKey privateKey2)
        {

            // Variables
            byte[] encryptedPassphraseAsBytes = null;
            encryptedPassphraseAsBytes = input.Reference;

            byte[] passphraseAsBytes = null;
            string passPhrase = null; // used for the legacy
            if (privateKey2 == null)
            {
                passphraseAsBytes = await privateKey1.UnwrapKeyAsync(encryptedPassphraseAsBytes);
                if (input.AsymmetricStrategy == AsymmetricStrategyOption.Legacy_Aes2)
                {
                    passPhrase = (string)Serializer.DeserializeFromByteArray(passphraseAsBytes);
                }
            }
            else
            {
                var dualPwJson = Encoding.UTF8.GetString(encryptedPassphraseAsBytes);
                var dualPw = Serializer.DeserializeFromJson<DualKeyProtectedPassword>(dualPwJson);

                var passPhrase1Bytes = await privateKey1.UnwrapKeyAsync(dualPw.EncryptedPassphrase1);
                var passPhrase2Bytes = await privateKey2.UnwrapKeyAsync(dualPw.EncryptedPassphrase2);

                if (input.AsymmetricStrategy == AsymmetricStrategyOption.Legacy_Aes2)
                {
                    var passPhrase1 = (string)Serializer.DeserializeFromByteArray(passPhrase1Bytes);
                    var passPhrase2 = (string)Serializer.DeserializeFromByteArray(passPhrase2Bytes);
                    passPhrase = passPhrase1 + passPhrase2;
                }
                else
                {
                    // generate the full passphrase
                    passphraseAsBytes = passPhrase1Bytes.Concat(passPhrase2Bytes).ToArray();
                }
                //passPhrase1Bytes.ClearByteArray();
                //passPhrase2Bytes.ClearByteArray();
            }

            object output = null;

            // handle the different strategies
            if (input.AsymmetricStrategy == AsymmetricStrategyOption.Undefined || input.AsymmetricStrategy == AsymmetricStrategyOption.Legacy_Aes2)
            {
                // deserialize the object using the legacy serialization to a string
                // unavoidable to preserve
#pragma warning disable 0618
                output = BasicEncryptor.DecryptObject(input.Data, input.CipherText, passPhrase);
#pragma warning restore 0618
            }
            else if (input.AsymmetricStrategy == AsymmetricStrategyOption.Aes256_5)
            {
                // decryption knows the iterations
                var decryptedObjectAsBytes = AesEncryptor.Decrypt(input.Data, passphraseAsBytes);
                output = Serializer.DeserializeFromByteArray(decryptedObjectAsBytes);
            }
            else if (input.AsymmetricStrategy == AsymmetricStrategyOption.Aes256_1000 || input.AsymmetricStrategy == AsymmetricStrategyOption.Aes256_5 || input.AsymmetricStrategy == AsymmetricStrategyOption.Aes256_200000)
            {
                // decryption knows the iterations
                var decryptedObjectAsBytes = AesEncryptor.Decrypt(input.Data, passphraseAsBytes);
                output = Serializer.DeserializeFromByteArray(decryptedObjectAsBytes);
            }
            else
            {
                throw new NotImplementedException(string.Format("AsymmetricStrategyOption '{0}' not implemented.", input.AsymmetricStrategy.ToString()));
            }

            passphraseAsBytes.ClearByteArray();

            return output;
        }
Example #38
0
 public KeyPair(IPublicKey publicKey, IPrivateKey privateKey)
 {
     PublicKey = publicKey;
     PrivateKey = privateKey;
 }
 public ISignatureCodec Sign(IPrivateKey privateKey, ByteBuf buffer)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// This may be used to decrypte a password used for symmetric encryption.
        /// </summary>
        /// <param name="encryptedValueAsBase64String"></param>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static async Task<SecureString> DecryptFromBase64StringAsync(string encryptedValueAsBase64String, IPrivateKey privateKey1, IPrivateKey privateKey2)
        {

            if (string.IsNullOrEmpty(encryptedValueAsBase64String))
            {
                throw new ArgumentException("encryptedValueAsBase64String");
            }

            byte[] plainBytes = null;

            // Read encrypted data
            var bytes = Convert.FromBase64String(encryptedValueAsBase64String);
            var json = Encoding.UTF8.GetString(bytes);
            var asymEncObj = Serializer.DeserializeFromJson<AsymmetricallyEncryptedObject>(json);

            // deserialize the object
            var asymEnc = new AsymmetricEncryptor();
            plainBytes = (byte[])await asymEnc.DecryptObjectAsync(asymEncObj, privateKey1, privateKey2);

            var secureString = new SecureString();
            var chars = System.Text.Encoding.UTF8.GetChars(plainBytes);
            foreach (var c in chars)
            {
                secureString.AppendChar(c);
            }
            for (int i = 0; i < chars.Length; i++)
            {
                // clear chars array
                chars[i] = 'X';
            }
            chars = null;
            return secureString;
        }
        public async Task<IPrivateKey> ToKeyEncyrptionKeyAsync(IPrivateKey keyProtector)
        {
            if (keyProtector == null)
            {
                throw new ArgumentNullException("keyProtector");
            }
            if (keyProtector.KeyId != _encryptedKey.KeyId)
            {
                throw new ArgumentException(string.Format("keyProtector.KeyId '{0}' does not match encryptedKey.KeyId '{1}'.", keyProtector.KeyId, _encryptedKey.KeyId));
            }

            // decrypt the key and populate to the x509
            var asymEnc = new AsymmetricEncryptor();
            var decrypted = await asymEnc.DecryptObjectAsync(_encryptedKey, keyProtector);

            var pfxBytes = (byte[])decrypted;
            if (decrypted == null || !pfxBytes.Any())
            {
                throw new CryptographicException(string.Format("encryptedKey successfull decrypted but was not a valid PFX byte array. Type was '{0}'.", decrypted.GetType().FullName));
            }
            IPrivateKey protectedKeyAsKeyEncryptionKey;
            try
            {
                var x509 = new X509Certificate2(pfxBytes);
                if (x509.Thumbprint.ToLower() != this.KeyId.ToLower())
                {
                    throw new System.Security.SecurityException(string.Format("The original KeyId '{0}' does not match the certificate thumbprint '{1}'.", this.KeyId, x509.Thumbprint));
                }
                if (x509.HasPrivateKey && x509.PrivateKey == null)
                {
                    var csp = x509.PrivateKey as RSACryptoServiceProvider;
                    if (csp == null)
                    {
                        throw new NotImplementedException(string.Format("encryptedKey does not have a valid RSACryptoServiceProvider private key. Type was '{0}'.", x509.PrivateKey.GetType().FullName));
                    }
                    if (csp.CspKeyContainerInfo.Exportable)
                    {
                        throw new System.Security.SecurityException("The decrypted X509Certificate2 was marked as exportable in the CspKeyContainerInfo. This is not permitted on a protected key.");
                    }
                }
                protectedKeyAsKeyEncryptionKey = Utilities.X509CertificateHelper.GetKeyEncryptionKey(x509);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(string.Format("X509Certificate2 could not be validated. Thumbprint '{0}'. See inner exception for details.", ex));
            }

            return protectedKeyAsKeyEncryptionKey;
        }
 public static SecureString DecryptFromBase64String(string encryptedValueAsBase64String, IPrivateKey privateKey)
 {
     return DecryptFromBase64String(encryptedValueAsBase64String, privateKey, null);
 }
 public static SecureString DecryptFromBase64String(string encryptedValueAsBase64String, IPrivateKey privateKey1, IPrivateKey privateKey2)
 {
     return AsyncHelper.RunSync(() => DecryptFromBase64StringAsync(encryptedValueAsBase64String, privateKey1, privateKey2));
 }