Esempio n. 1
0
        /// <summary>
        /// Initializes the facade. Should only be called once.
        /// </summary>
        /// <param name="context">An Android Context object. Usually the Activity object.</param>
        /// <param name="developerUuid">The developer UUID, which is obtained from the developer portal.</param>
        public void Init(Android.Content.Context context, string developerUuid)
        {
            // Load the key from the resources
            byte[] applicationKey = null;
            var resId = context.Resources.GetIdentifier("key", "raw", context.PackageName);
            using (var stream = context.Resources.OpenRawResource(resId))
            {
                using (var ms = new MemoryStream())
                {
                    stream.CopyTo(ms);
                    applicationKey = ms.ToArray();
                }
            }
            
            // Generate the public key from the application key
            using (var keySpec = new X509EncodedKeySpec(applicationKey))
            {
                using (var keyFactory = KeyFactory.GetInstance("RSA"))
                {
                    _publicKey = keyFactory.GeneratePublic(keySpec);
                }
            }

            InitInternal(context, developerUuid);
            OuyaController.Init(context);

            Log("Hardware: " + GetDeviceHardware().DeviceName());
        }
        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 PurchaseListener(TaskCompletionSource<bool> tcs, IPublicKey publicKey, Product product, string uniquePurchaseId)
 {
     _tcs = tcs;
     _publicKey = publicKey;
     _product = product;
     _uniquePurchaseId = uniquePurchaseId;
 }
 public static async Task<string> EncryptToBase64StringAsync(SecureString passwordToProtect, IPublicKey publicKey)
 {
     if (publicKey == null)
     {
         throw new ArgumentNullException(nameof(publicKey));
     }
     //var rsa = X509CertificateHelper.GetRSACryptoServiceProviderFromPublicKey(publicKey);
     return await EncryptToBase64StringAsync(passwordToProtect, publicKey, null);
 }
        public void EncodePublicKey(IPublicKey publicKey, ByteBuf buffer)
        {
            var dsa = new DSACryptoServiceProvider();
            var dsap = dsa.ExportParameters(false);


            var rsa = new RSACryptoServiceProvider();
            var rsap = rsa.ExportParameters(false);


        }
Esempio n. 6
0
        /// <summary>
        /// Verify the specified publicKey, signedData and signature.
        /// </summary>
        /// <param name="publicKey">Public key.</param>
        /// <param name="signedData">Signed data.</param>
        /// <param name="signature">Signature.</param>
        public static bool Verify(IPublicKey publicKey, string signedData, string signature)
        {
            Logger.Debug ("Signature: {0}", signature);
            try {
                var sign = Signature.GetInstance (SignatureAlgorithm);
                sign.InitVerify (publicKey);
                sign.Update (Encoding.UTF8.GetBytes (signedData));

                if (!sign.Verify (Base64.Decode (signature, 0))) {
                    Logger.Error ("Security. Signature verification failed.");
                    return false;
                }

                return true;
            } catch (Exception e) {
                Logger.Error (e.Message);
            }

            return false;
        }
 public static bool Verify(IPublicKey publicKey, string signedData, string signature)
 {
     object[] args = new object[] { signature };
     Logger.Debug("Signature: {0}", args);
     try
     {
         Signature instance = Signature.GetInstance("SHA1withRSA");
         instance.InitVerify(publicKey);
         instance.Update(Encoding.UTF8.GetBytes(signedData));
         if (!instance.Verify(Base64.Decode(signature, 0)))
         {
             Logger.Error("Security. Signature verification failed.", new object[0]);
             return false;
         }
         return true;
     }
     catch (System.Exception exception)
     {
         Logger.Error(exception.Message, new object[0]);
     }
     return false;
 }
        //private X509Certificate2 _x5092;

        #region properties



        #endregion

        #region .ctors



        #endregion

        #region methods

        public async Task<ProtectedX509Certificate2> IssueNewCertificateAsync(IPublicKey keyProtector, ICertificatePolicy certificatePolicy)
        {            
            if (keyProtector == null)
            {
                throw new ArgumentNullException("keyProtectorPublicKey");
            }

            //if (keyProtector.PublicKey == null)
            //{
            //    throw new ArgumentNullException("keyProtectorPublicKey.PublicKey");
            //}

            //var publicKeyProvider = keyProtector.PublicKey.Key as RSACryptoServiceProvider;
            //if (publicKeyProvider == null)
            //{
            //    throw new NotImplementedException("keyProtectorPublicKey.PublicKey.Key must be a valid RSACryptoServiceProvider");
            //}

            string thumbprint;
            string pemPublicCert;
            byte[] pkcs12Data;

            System.Security.Cryptography.X509Certificates.X509Certificate2 x509Certificate2;

            GenerateSigningCertificate(certificatePolicy, out thumbprint, out pemPublicCert, out pkcs12Data, out x509Certificate2);

            // encrypt the password using our primary certificate

            var encryptor = new AsymmetricEncryptor() { AsymmetricStrategy = AsymmetricStrategyOption.Aes256_1000 };

            var asymEncObj = encryptor.EncryptObjectAsync(pkcs12Data, keyProtector).GetAwaiter().GetResult();
            if (string.IsNullOrEmpty(asymEncObj.KeyId) || asymEncObj.KeyId.Length != 40)
            {
                throw new InvalidOperationException("AsymmetricEncryptor.EncryptObject returned without KeyId populated.");
            }
            var protectedKey = new ProtectedX509Certificate2(x509Certificate2.Thumbprint.ToLower(), asymEncObj);
            return await Task.FromResult(protectedKey);
        }
 /// <summary>
 /// Verifies that the signature from the server matches the computed
 /// signature on the data.  Returns true if the data is correctly signed.
 /// </summary>
 /// <param name="publicKey"> public key associated with the developer account </param>
 /// <param name="signedData"> signed data from server </param>
 /// <param name="signature"> server signature </param>
 /// <returns> true if the data and signature match </returns>
 public static bool Verify(IPublicKey publicKey, string signedData, string signature)
 {
     if (Consts.DEBUG)
     {
         Log.Info(TAG, "signature: " + signature);
     }
     Signature sig;
     try
     {
         sig = Signature.GetInstance(SIGNATURE_ALGORITHM);
         sig.InitVerify(publicKey);
         sig.Update(Encoding.UTF8.GetBytes(signedData));
         if (!sig.Verify(Convert.FromBase64String(signature)))
         {
             Log.Error(TAG, "Signature verification failed.");
             return false;
         }
         return true;
     }
     catch (NoSuchAlgorithmException e)
     {
         Log.Error(TAG, "NoSuchAlgorithmException.");
     }
     catch (InvalidKeyException e)
     {
         Log.Error(TAG, "Invalid key specification.");
     }
     catch (SignatureException e)
     {
         Log.Error(TAG, "Signature exception.");
     }
     catch (FormatException e)
     {
         Log.Error(TAG, "Base64 decoding failed.");
     }
     return false;
 }
Esempio n. 10
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="publicKey"></param>
		/// <param name="signedData"></param>
		/// <param name="signature"></param>
		/// <returns></returns>
		public static bool Verify(IPublicKey publicKey, string signedData, string signature)
		{
			Utils.LogDebug("Signature: " + signature);
			Signature sig;

			try
			{
				sig = Signature.GetInstance(SIGNATURE_ALGORITHM);
				sig.InitVerify(publicKey);
				sig.Update(Encoding.UTF8.GetBytes(signedData));

				if (!sig.Verify(Base64.Decode(signature, 0)))
				{
					Utils.LogError("Security. Signature verification failed.");
					return false;
				}
				return true;
			}
			catch (NoSuchAlgorithmException e)
			{
				Utils.LogError("Security. NoSuchAlgorithmException.");
			}
			catch (InvalidKeyException e)
			{
				Utils.LogError("Security. Invalid key specification.");
			}
			catch (SignatureException e)
			{
				Utils.LogError("Security. Signature exception.");
			}
			catch (Base64DecoderException e)
			{
				Utils.LogError("Security. Base64 decoding failed.");
			}
			return false;
		}
        //[Obsolete]
        //public static string EncryptToBase64String(SecureString passwordToProtect, string keyId, RSACryptoServiceProvider publicKey)
        //{
        //    return EncryptToBase64String(passwordToProtect, keyId, publicKey, null, null);
        //}


        ///// <summary>
        ///// This may be used to secure a password for symmetric encryption.
        ///// </summary>
        ///// <param name="passwordToProtect"></param>
        ///// <param name="publicKey"></param>
        ///// <returns></returns>
        //[Obsolete("Use the IPublicKey infrastructure")]
        //public static string EncryptToBase64String(SecureString passwordToProtect, string key1Id, RSACryptoServiceProvider publicKey1, string key2Id, RSACryptoServiceProvider publicKey2)
        //{
        //    // Use a 4-byte array to fill it with random bytes and convert it then
        //    // to an integer value.
        //    byte[] plainBytes;
        //    //byte[] encryptedBytes = null;

        //    plainBytes = passwordToProtect.ToByteArray();

        //    var asymEnc = new AsymmetricEncryptor(AsymmetricStrategyOption.Aes256_1000);
        //    var asymObj = asymEnc.EncryptObject(plainBytes, key1Id, publicKey1, key2Id, publicKey2);
        //    var json = Serializer.SerializeToJson(asymObj);
        //    var bytes = Encoding.UTF8.GetBytes(json);
        //    return Convert.ToBase64String(bytes);
        //}

        /// <summary>
        /// This may be used to secure a password for symmetric encryption.
        /// </summary>
        /// <param name="passwordToProtect"></param>
        /// <param name="publicKey"></param>
        /// <returns></returns>
        public static async Task <string> EncryptToBase64StringAsync(SecureString passwordToProtect, IPublicKey publicKey1, IPublicKey publicKey2)
        {
            // Use a 4-byte array to fill it with random bytes and convert it then
            // to an integer value.
            byte[] plainBytes;
            //byte[] encryptedBytes = null;

            plainBytes = passwordToProtect.ToByteArray();

            var asymEnc = new AsymmetricEncryptor(AsymmetricStrategyOption.Aes256_1000);
            var asymObj = await asymEnc.EncryptObject_PrivateAsync(plainBytes, publicKey1, publicKey2);

            var json  = Serializer.SerializeToJson(asymObj);
            var bytes = Encoding.UTF8.GetBytes(json);

            return(Convert.ToBase64String(bytes));
        }
Esempio n. 12
0
 public bool Verify(IPublicKey publicKey, ByteBuf buffer, ISignatureCodec signatureEncoded)
 {
     throw new NotImplementedException();
 }
Esempio n. 13
0
        private bool CanProtectDomain(Number160 domainKey, IPublicKey publicKey)
        {
		    if (IsDomainRemoved(domainKey))
            {
			    return false;
		    }
		    if (ProtectionDomainEnable == ProtectionEnable.All)
            {
			    return true;
		    } 
            if (ProtectionDomainEnable == ProtectionEnable.None) 
            {
			    // only if we have the master key
			    return ForceOverrideDomain(domainKey, publicKey);
		    }
		    return false;
	    }
Esempio n. 14
0
        private static bool IsMine(Number160 key, IPublicKey publicKey)
        {
		    return key.Equals(Utils.MakeShaHash(publicKey.GetEncoded()));
	    }
Esempio n. 15
0
        private bool ForceOverrideDomain(Number160 domainKey, IPublicKey publicKey)
        {
		    // we are in public key mode
		    if (ProtectionDomainMode == ProtectionMode.MasterPublicKey && publicKey != null)
            {
			    // if the hash of the public key is the same as the domain, we can overwrite
			    return IsMine(domainKey, publicKey);
		    }
		    return false;
	    }
Esempio n. 16
0
        private bool CanClaimDomain(Number320 key, IPublicKey publicKey)
        {
		    var domainProtectedByOthers = _backend.IsDomainProtectedByOthers(key, publicKey);
		    var domainOverridableByMe = ForceOverrideDomain(key.DomainKey, publicKey);
		    return !domainProtectedByOthers || domainOverridableByMe;
	    }
Esempio n. 17
0
 public abstract byte[] ExportPublicKey(IPublicKey publicKey);
Esempio n. 18
0
        private bool SecurityDomainCheck(Number320 key, IPublicKey publicKey, IPublicKey newPublicKey, bool domainProtection) 
        {
		    var domainProtectedByOthers = _backend.IsDomainProtectedByOthers(key, publicKey);
			Logger.Debug("No domain protection requested {0} for domain {1}.", Utils.Hash(newPublicKey), key);
		    // I dont want to claim the domain
		    if (!domainProtection)
            {
                // Returns true if the domain is not protceted by others, otherwise
			    // false if the domain is protected
			    return !domainProtectedByOthers;
		    }
            if (CanClaimDomain(key, publicKey))
            {
                if (CanProtectDomain(key.DomainKey, publicKey))
                {
                    Logger.Debug("Set domain protection.");
                    return _backend.ProtectDomain(key, newPublicKey);
                }
                return true;
            }
            return false;
	    }
Esempio n. 19
0
 public Data SetPublicKey(IPublicKey publicKey)
 {
     PublicKey    = publicKey;
     HasPublicKey = true;
     return(this);
 }
Esempio n. 20
0
 public ReceiptsListener(TaskCompletionSource <IList <Receipt> > tcs, IPublicKey publicKey, string gamerUuid)
 {
     _tcs       = tcs;
     _publicKey = publicKey;
     _gamerUuid = gamerUuid;
 }
Esempio n. 21
0
 public bool Verify(IPublicKey publicKey, ISignatureFactory signatureFactory)
 {
     return(signatureFactory.Verify(publicKey, _buffer.ToByteBuf(), Signature));
 }
Esempio n. 22
0
 public KeyPair(IPublicKey publicKey, IPrivateKey privateKey)
 {
     PublicKey  = publicKey;
     PrivateKey = privateKey;
 }
Esempio n. 23
0
        private KeyPair rsaKeyFromBytes(byte [] keyBytes)
        {
            try
            {
                int offset  = 0;
                int dataLen = 0;
                int version = 0;

                if (keyBytes.Length != 523 && keyBytes.Length != 2339)
                {
                    offset += 1; // skip address version
                    version = BitConverter.ToInt32(keyBytes, offset);
                    offset += 4;
                }

                dataLen = BitConverter.ToInt32(keyBytes, offset);
                offset += 4;
                Java.Math.BigInteger modulus = bigEndianToLittleEndian(keyBytes.Skip(offset).Take(dataLen).ToArray());
                offset += dataLen;

                dataLen = BitConverter.ToInt32(keyBytes, offset);
                offset += 4;
                Java.Math.BigInteger exponent = bigEndianToLittleEndian(keyBytes.Skip(offset).Take(dataLen).ToArray());
                offset += dataLen;

                RSAPrivateCrtKeySpec privKeySpec = null;

                if (keyBytes.Length > offset)
                {
                    dataLen = BitConverter.ToInt32(keyBytes, offset);
                    offset += 4;
                    Java.Math.BigInteger P = bigEndianToLittleEndian(keyBytes.Skip(offset).Take(dataLen).ToArray());
                    offset += dataLen;

                    dataLen = BitConverter.ToInt32(keyBytes, offset);
                    offset += 4;
                    Java.Math.BigInteger Q = bigEndianToLittleEndian(keyBytes.Skip(offset).Take(dataLen).ToArray());
                    offset += dataLen;

                    dataLen = BitConverter.ToInt32(keyBytes, offset);
                    offset += 4;
                    Java.Math.BigInteger DP = bigEndianToLittleEndian(keyBytes.Skip(offset).Take(dataLen).ToArray());
                    offset += dataLen;

                    dataLen = BitConverter.ToInt32(keyBytes, offset);
                    offset += 4;
                    Java.Math.BigInteger DQ = bigEndianToLittleEndian(keyBytes.Skip(offset).Take(dataLen).ToArray());
                    offset += dataLen;

                    dataLen = BitConverter.ToInt32(keyBytes, offset);
                    offset += 4;
                    Java.Math.BigInteger InverseQ = bigEndianToLittleEndian(keyBytes.Skip(offset).Take(dataLen).ToArray());
                    offset += dataLen;

                    dataLen = BitConverter.ToInt32(keyBytes, offset);
                    offset += 4;
                    Java.Math.BigInteger D = bigEndianToLittleEndian(keyBytes.Skip(offset).Take(dataLen).ToArray());
                    offset     += dataLen;
                    privKeySpec = new RSAPrivateCrtKeySpec(modulus, exponent, D, P, Q, DP, DQ, InverseQ);
                }

                RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, exponent);

                KeyFactory  keyFactory = KeyFactory.GetInstance("RSA");
                IPublicKey  pubKey     = keyFactory.GeneratePublic(pubKeySpec);
                IPrivateKey privKey    = null;
                if (privKeySpec != null)
                {
                    privKey = keyFactory.GeneratePrivate(privKeySpec);
                }

                return(new KeyPair(pubKey, privKey));
            }catch (Exception)
            {
                Logging.warn("An exception occured while trying to reconstruct PKI from bytes");
            }
            return(null);
        }
 public async Task <AsymmetricallyEncryptedObject> EncryptObjectAsync(object input, IPublicKey publicKey1, IPublicKey publicKey2)
 {
     // temporary... need to shift to create a password and wrap or unwrap in future
     //var rsa1 = publicKey1.ToRSACryptoServiceProvider();
     //var rsa2 = publicKey2.ToRSACryptoServiceProvider();
     return(await this.EncryptObject_PrivateAsync(input, publicKey1, publicKey2));
 }
Esempio n. 25
0
 public abstract byte[] DecryptThenVerify(byte[] cipherData, IPrivateKey privateKey, IPublicKey publicKey);
Esempio n. 26
0
        public SortedDictionary<Number640, byte> RemoveReturnStatus(Number640 from, Number640 to, IPublicKey publicKey)
        {
		    var rLock = RangeLock.Lock(from, to);
		    try
            {
			    var tmp = _backend.SubMap(from, to, -1, true);
			    var result = new SortedDictionary<Number640, byte>();
			    foreach (var key in tmp.Keys)
                {
				    var pair = Remove(key, publicKey, false);
				    result.Put(key, (byte) Convert.ToInt32(pair.Element1)); // TODO check if works
			    }
			    return result;
		    }
            finally
            {
			    rLock.Unlock();
		    }
	    }
Esempio n. 27
0
 public abstract bool Verify(byte[] data, byte[] signature, IPublicKey signerKey);
Esempio n. 28
0
        private bool SecurityEntryCheck(Number480 key, IPublicKey publicKeyMessage, IPublicKey publicKeyData, bool entryProtection) 
        {
		    var entryProtectedByOthers = _backend.IsEntryProtectedByOthers(key, publicKeyMessage);
		    // I dont want to claim the domain
		    if (!entryProtection)
            {
			    // Returns true if the domain is not protceted by others, otherwise
			    // false if the domain is protected
			    return !entryProtectedByOthers;
		    }
            //replication cannot sign messages with the originators key, so we must also check the public key of the data
            if (CanClaimEntry(key, publicKeyMessage) || CanClaimEntry(key, publicKeyData))
            {
                if (CanProtectEntry(key.DomainKey, publicKeyMessage))
                {
                    return _backend.ProtectEntry(key, publicKeyData);
                }
                return true;
            }
            return false;
	    }
        private async Task <AsymmetricallyEncryptedObject> EncryptObject_PrivateAsync(object input, IPublicKey publicKey1, IPublicKey publicKey2)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }
            if (publicKey1 == null)
            {
                throw new ArgumentNullException(nameof(publicKey1));
            }

            //if (string.IsNullOrEmpty(key1Id))
            //{
            //    throw new ArgumentException("key1Id");
            //}
            //if (publicKey2 != null && string.IsNullOrEmpty(key2Id))
            //{
            //    throw new ArgumentException("key2Id");
            //}
            //if (!string.IsNullOrEmpty(key2Id) && publicKey2 == null)
            //{
            //    throw new ArgumentNullException("publicKey2");
            //}

            // password lengths



            int pwLen = 32;

            //var pwMinLen = pwLen;
            //var pwMaxLen = pwLen; // 40;

            if (this.AsymmetricStrategy == AsymmetricStrategyOption.Aes256_1000)
            {
                pwLen = 40;
                //// up the pw size
                //pwMinLen = 40;
                //pwMaxLen = 40;
            }

            //if (pwMinLen < 32)
            //{
            //    throw new NotImplementedException("pwMinLen is at least 32 bytes");
            //}

            //if (pwMinLen == pwMaxLen)
            //{
            //    pwLen = pwMaxLen;
            //}
            //else
            //{
            //    pwLen = rand.RandomNumber(pwMinLen, pwMaxLen);
            //}


            byte[] passPhraseAsBytes  = null;
            byte[] passPhrase2AsBytes = null;

            string passPhrase  = null;
            string passPhrase2 = null;

            var cryptoSvc = RNGCryptoServiceProvider.Create();

            if (this.AsymmetricStrategy == AsymmetricStrategyOption.Legacy_Aes2)
            {
                // legacy uses a string
                var rand = new RandomGenerator();
                passPhrase        = rand.GenerateSecretCodeUrlSafe(pwLen, pwLen); // pwMinLen, pwMaxLen);
                passPhraseAsBytes = Serializer.SerializeToByteArray(passPhrase);
                if (publicKey2 != null)
                {
                    passPhrase2        = rand.GenerateSecretCodeUrlSafe(pwLen, pwLen); // pwMinLen, pwMaxLen);
                    passPhrase2AsBytes = Serializer.SerializeToByteArray(passPhrase2);
                }
            }
            else
            {
                passPhraseAsBytes = new byte[pwLen];
                cryptoSvc.GetBytes(passPhraseAsBytes);
                if (publicKey2 != null)
                {
                    passPhrase2AsBytes = new byte[pwLen];
                    cryptoSvc.GetBytes(passPhrase2AsBytes);
                }
            }

            byte[] encryptedPassPhraseAsBytes        = null;
            AsymmetricallyEncryptedObject asymEncObj = null;

            byte[] encryptionPassPhrase = null;

            // if there are two keys, then we double encrypt the passphrase
            if (publicKey2 == null)
            {
                var encRes = await publicKey1.WrapKeyAsync(passPhraseAsBytes);

                encryptedPassPhraseAsBytes = encRes;
                asymEncObj = new AsymmetricallyEncryptedObject()
                {
                    KeyId     = publicKey1.KeyId,
                    Reference = encryptedPassPhraseAsBytes
                };
                encryptionPassPhrase = passPhraseAsBytes;
            }
            else
            {
                // double passwords
                var dualPw = new DualKeyProtectedPassword();

                // get encryption from key1
                var encRes1 = await publicKey1.WrapKeyAsync(passPhraseAsBytes);

                dualPw.EncryptedPassphrase1 = encRes1;

                // get encryption from key2
                var encRes2 = await publicKey2.WrapKeyAsync(passPhrase2AsBytes);

                dualPw.EncryptedPassphrase2 = encRes2;

                encryptedPassPhraseAsBytes = Encoding.UTF8.GetBytes(Serializer.SerializeToJson(dualPw));

                asymEncObj = new AsymmetricallyEncryptedObject()
                {
                    KeyId     = publicKey1.KeyId,
                    Key2Id    = publicKey2.KeyId,
                    Reference = encryptedPassPhraseAsBytes
                };

                encryptionPassPhrase = passPhraseAsBytes.Concat(passPhrase2AsBytes).ToArray();
            }

            // handle the different strategies
            // handle the different strategies
            if (this.AsymmetricStrategy == AsymmetricStrategyOption.Legacy_Aes2)
            {
                // this is the revised legacy handling that has been enhanced

                // Note that the passPhrase is a string, but the reference taht is stored is
                // -----> Serializer.SerializeToByteArray(passPhrase);
                //        This is not a straight forward string to byte array conversion using encoding.
                //        And the decrypte expects to use this serializer method.

                string cipher;
#pragma warning disable 0618
                asymEncObj.Data = BasicEncryptor.EncryptObject(input, passPhrase + passPhrase2, out cipher);
#pragma warning restore 0618
                asymEncObj.CipherText         = cipher;
                asymEncObj.AsymmetricStrategy = AsymmetricStrategyOption.Legacy_Aes2; // critical!!!
            }
            else if (this.AsymmetricStrategy == AsymmetricStrategyOption.Aes256_20000)
            {
                byte[] inputAsBytes = Serializer.SerializeToByteArray(input);
                asymEncObj.Data = AesEncryptor.Encrypt20000(inputAsBytes, encryptionPassPhrase);
                asymEncObj.AsymmetricStrategy = AsymmetricStrategyOption.Aes256_20000; // critical!!!
            }
            else if (this.AsymmetricStrategy == AsymmetricStrategyOption.Undefined || this.AsymmetricStrategy == AsymmetricStrategyOption.Aes256_1000)
            {
                byte[] inputAsBytes = Serializer.SerializeToByteArray(input);
                asymEncObj.Data = AesEncryptor.Encrypt1000(inputAsBytes, encryptionPassPhrase);
                asymEncObj.AsymmetricStrategy = AsymmetricStrategyOption.Aes256_1000; // critical!!!
            }
            else if (this.AsymmetricStrategy == AsymmetricStrategyOption.Aes256_5)
            {
                byte[] inputAsBytes = Serializer.SerializeToByteArray(input);
                asymEncObj.Data = AesEncryptor.Encrypt5(inputAsBytes, encryptionPassPhrase);
                asymEncObj.AsymmetricStrategy = AsymmetricStrategyOption.Aes256_5; // critical!!!
            }
            else
            {
                throw new NotImplementedException(string.Format("AsymmetricStrategyOption '{0}' not implemented.", this.AsymmetricStrategy.ToString()));
            }

            passPhraseAsBytes.ClearByteArray();
            passPhrase2AsBytes.ClearByteArray();

            return(asymEncObj);
        }
Esempio n. 30
0
        private bool ForceOverrideEntry(Number160 entryKey, IPublicKey publicKey)
        {
		    // we are in public key mode
		    if (ProtectionEntryMode == ProtectionMode.MasterPublicKey && publicKey?.GetEncoded() != null)
            {
			    // if the hash of the public key is the same as the domain, we can overwrite
			    return IsMine(entryKey, publicKey);
		    }
		    return false;
	    }
 public byte[] ExportPublicKey(IPublicKey publicKey)
 {
     throw new NotImplementedException();
 }
Esempio n. 32
0
        private bool CanClaimEntry(Number480 key, IPublicKey publicKey)
        {
		    var entryProtectedByOthers = _backend.IsEntryProtectedByOthers(key, publicKey);
		    var entryOverridableByMe = ForceOverrideEntry(key.ContentKey, publicKey);
		    return !entryProtectedByOthers || entryOverridableByMe;
	    }
Esempio n. 33
0
        public Enum UpdateMeta(IPublicKey publicKey, Number640 key, Data newData)
        {
		    var rangeLock = Lock(key);
		    try 
            {
			    if (!SecurityEntryCheck(key.LocationAndDomainAndContentKey, publicKey, newData.PublicKey,
			            newData.IsProtectedEntry))
                {
				    return PutStatus.FailedSecurity;
			    }

			    var data = _backend.Get(key);
			    var changed = false;
			    if (data != null && newData.PublicKey != null)
                {
				    data.SetPublicKey(newData.PublicKey);
				    changed = true;
			    }
			    if (data != null && newData.IsSigned)
                {
				    data.SetSignature(newData.Signature);
				    changed = true;
			    }
			    if (data != null)
                {
				    data.SetValidFromMillis(newData.ValidFromMillis);
				    data.SetTtlSeconds(newData.TtlSeconds);
				    changed = true;
			    }
			    if (changed)
                {
				    long expiration = data.ExpirationMillis;
				    // handle timeout
				    _backend.AddTimeout(key, expiration);
				    _backend.Put(key, data);
				    return PutStatus.Ok;
			    } else
                {
				    return PutStatus.NotFound;
			    }
		    } 
            finally 
            {
			    rangeLock.Unlock();
		    }
	    }
Esempio n. 34
0
        private bool CanProtectEntry(Number160 contentKey, IPublicKey publicKey)
        {
		    if (ProtectionEntryEnable == ProtectionEnable.All)
            {
			    return true;
		    } 
            if (ProtectionEntryEnable == ProtectionEnable.None)
            {
			    // only if we have the master key
			    return ForceOverrideEntry(contentKey, publicKey);
		    }
		    return false;
	    }
Esempio n. 35
0
 /// <summary>
 /// Load a KeyPair
 /// </summary>
 /// <param name="privKey">Secret Private Key</param>
 /// <param name="pubKey">Public Key</param>
 public SigningKeyPair(IPrivateSecretKey privKey, IPublicKey pubKey)
 {
     Secret = privKey ?? throw new ArgumentNullException(nameof(privKey));
     Public = pubKey ?? throw new ArgumentNullException(nameof(pubKey));
 }
Esempio n. 36
0
        public Enum UpdateMeta(Number320 locationAndDomainKey, IPublicKey publicKey, IPublicKey newPublicKey)
        {
		    if (!SecurityDomainCheck(locationAndDomainKey, publicKey, newPublicKey, true))
            {
			    return PutStatus.FailedSecurity;
		    }
		    return PutStatus.Ok;
	    }
 public static async Task <string> EncryptToBase64StringAsync(SecureString passwordToProtect, IPublicKey publicKey)
 {
     if (publicKey == null)
     {
         throw new ArgumentNullException(nameof(publicKey));
     }
     //var rsa = X509CertificateHelper.GetRSACryptoServiceProviderFromPublicKey(publicKey);
     return(await EncryptToBase64StringAsync(passwordToProtect, publicKey, null));
 }
Esempio n. 38
0
        public Enum PutConfirm(IPublicKey publicKey, Number640 key, Data newData)
        {
		    var rangeLock = Lock(key);
		    try 
            {
			    if (!SecurityEntryCheck(key.LocationAndDomainAndContentKey, publicKey, newData.PublicKey, newData.IsProtectedEntry))
                {
				    return PutStatus.FailedSecurity;
			    }

			    var data = _backend.Get(key);
			    if (data != null)
                {
				    // remove prepare flag
                    data.SetHasPreparaFlag(false);
				    data.SetValidFromMillis(newData.ValidFromMillis);
				    data.SetTtlSeconds(newData.TtlSeconds);

				    var expiration = data.ExpirationMillis;
				    // handle timeout
				    _backend.AddTimeout(key, expiration);
				    _backend.Put(key, data);
				    return PutStatus.Ok;
			    } else {
				    return PutStatus.NotFound;
			    }
		    } 
            finally 
            {
			    rangeLock.Unlock();
		    }
		    // TODO: Java: check for FORKS!
	    }
Esempio n. 39
0
 /// <inheritdoc />
 public byte[] ExportPublicKey(IPublicKey publicKey)
 {
     return(publicKey.Bytes);
 }
Esempio n. 40
0
 public Byte64 CTransactionEntry(IPublicKey publicKey, Byte32 value, Byte32 blinding, Byte32 totalFees, int noParticipants)
 {
     throw new NotImplementedException();
 }
Esempio n. 41
0
        public SortedDictionary<Number640, Data> RemoveReturnData(Number640 from, Number640 to, IPublicKey publicKey)
        {
		    var rLock = RangeLock.Lock(from, to);
		    try
            {
			    var tmp = _backend.SubMap(from, to, -1, true);

			    foreach (var key in tmp.Keys)
                {
				    // fail fast, as soon as we want to remove 1 domain that we cannot, abort
				    if (!CanClaimDomain(key.LocationAndDomainKey, publicKey))
                    {
					    return null;
				    }
				    if (!CanClaimEntry(key.LocationAndDomainAndContentKey, publicKey))
                    {
					    return null;
				    }
			    }
			    var result = _backend.Remove(from, to, true);
			    foreach (var kvp in result)
                {
				    var data = kvp.Value;
				    if (data.PublicKey == null || data.PublicKey.Equals(publicKey))
                    {
					    _backend.RemoveTimeout(kvp.Key);
				    }
			    }
			    return result;
		    }
            finally
            {
			    rLock.Unlock();
		    }
	    }
Esempio n. 42
0
 public RSACryptoServiceProvider Update(IPublicKey publicKey, MemoryStream[] buffers)
 {
     throw new NotImplementedException();
 }
 public AsymmetricallyEncryptedObject EncryptObject(object input, IPublicKey publicKey1, IPublicKey publicKey2)
 {
     return(AsyncHelper.RunSync(() => this.EncryptObjectAsync(input, publicKey1, publicKey2)));
 }
Esempio n. 44
0
 /// <summary>
 /// Initializes a new instance of the <see cref="KeyPair"/> class.
 /// </summary>
 public KeyPair(IPublicKey publicKey, IPrivateKey privateKey)
 {
     this.PublicKey  = publicKey;
     this.PrivateKey = privateKey;
 }
Esempio n. 45
0
 public bool Equals(IPublicKey other) => ToString().Equals(other.ToNullableString());
Esempio n. 46
0
 public Message SetPublicKey0(IPublicKey publicKey)
 {
     if (_publicKeyList == null)
     {
         _publicKeyList = new List<IPublicKey>(1);
     }
     _publicKeyList.Add(publicKey);
     return this;
 }
Esempio n. 47
0
 public Message SetPublicKey(IPublicKey publicKey)
 {
     if (!_presetContentTypes)
     {
         SetContentType(Content.PublicKey);
     }
     if (_publicKeyList == null)
     {
         _publicKeyList = new List<IPublicKey>(1);
     }
     _publicKeyList.Add(publicKey);
     return this;
 }
Esempio n. 48
0
        public Pair<Data, Enum> Remove(Number640 key, IPublicKey publicKey, bool returnData)
        {
		    var rangeLock = Lock(key);
		    try 
            {
			    if (!CanClaimDomain(key.LocationAndDomainKey, publicKey))
                {
				    return new Pair<Data, Enum>(null, PutStatus.FailedSecurity);
			    }
			    if (!CanClaimEntry(key.LocationAndDomainAndContentKey, publicKey))
                {
				    return new Pair<Data, Enum>(null, PutStatus.FailedSecurity);
			    }
			    if (!_backend.Contains(key))
                {
				    return new Pair<Data, Enum>(null, PutStatus.NotFound);
			    }
			    _backend.RemoveTimeout(key);
			    return new Pair<Data, Enum>(_backend.Remove(key, returnData), PutStatus.Ok);
		    } 
            finally
            {
			    rangeLock.Unlock();
		    }
	    }
Esempio n. 49
-1
        /// <summary>
        /// Initializes a new instance of the <see cref="RsaCryptographicKey" /> class.
        /// </summary>
        /// <param name="publicKey">The public key.</param>
        /// <param name="parameters">The RSA instance, if available.</param>
        /// <param name="algorithm">The algorithm.</param>
        internal RsaCryptographicKey(IPublicKey publicKey, RSAParameters parameters, AsymmetricAlgorithm algorithm)
        {
            Requires.NotNull(publicKey, "publicKey");

            this.publicKey = publicKey.JavaCast<IRSAPublicKey>();
            this.parameters = parameters;
            this.algorithm = algorithm;
        }