Example #1
0
        public override void ConfirmPassword(String password, byte[] keySpec,
                                             byte[] keySalt, byte[] verifier, byte[] verifierSalt,
                                             byte[] integritySalt)
        {
            BinaryRC4EncryptionVerifier ver = builder.GetVerifier();

            ver.SetSalt(verifierSalt);
            ISecretKey skey = BinaryRC4Decryptor.GenerateSecretKey(password, ver);

            SetSecretKey(skey);
            try
            {
                Cipher cipher            = BinaryRC4Decryptor.InitCipherForBlock(null, 0, builder, skey, Cipher.ENCRYPT_MODE);
                byte[] encryptedVerifier = new byte[16];
                cipher.Update(verifier, 0, 16, encryptedVerifier);
                ver.EncryptedVerifier = (encryptedVerifier);
                HashAlgorithm hashAlgo              = ver.HashAlgorithm;
                MessageDigest hashAlg               = CryptoFunctions.GetMessageDigest(hashAlgo);
                byte[]        calcVerifierHash      = hashAlg.Digest(verifier);
                byte[]        encryptedVerifierHash = cipher.DoFinal(calcVerifierHash);
                ver.EncryptedVerifierHash = (encryptedVerifierHash);
            }
            catch (Exception e)
            {
                throw new EncryptedDocumentException("Password Confirmation failed", e);
            }
        }
Example #2
0
        private async Task <byte[]> GetEncryptionKeyLockedAsync(string keyName)
        {
            byte[] key = null;

            try
            {
                char[]   deviceId = GetDeviceId().ToCharArray();
                KeyStore keyStore = await GetOrCreateKeyStoreAsync(deviceId).ConfigureAwait(false);

                KeyStore.IProtectionParameter protectionParameter = new KeyStore.PasswordProtection(deviceId);
                KeyStore.SecretKeyEntry       secretKeyEntry      = (KeyStore.SecretKeyEntry)keyStore.GetEntry(keyName, protectionParameter);

                if (secretKeyEntry != null)
                {
                    ISecretKey secretKey = secretKeyEntry.SecretKey;
                    if (secretKey != null)
                    {
                        key = secretKey.GetEncoded();
                    }
                }
            }
            catch (FileNotFoundException)
            {
                // If the file isn't found, it's not a big deal and should mean it's just the first run.
                // The caller or the GetOrCreate method above will need to create it if we don't find it here.
            }

            return(key);
        }
Example #3
0
        public override void ConfirmPassword(String password, byte[] keySpec,
                                             byte[] keySalt, byte[] verifier, byte[] verifierSalt,
                                             byte[] integritySalt)
        {
            Debug.Assert(verifier != null && verifierSalt != null);
            CryptoAPIEncryptionVerifier ver = builder.GetVerifier();

            ver.SetSalt(verifierSalt);
            ISecretKey skey = CryptoAPIDecryptor.GenerateSecretKey(password, ver);

            SetSecretKey(skey);
            try
            {
                Cipher cipher            = InitCipherForBlock(null, 0);
                byte[] encryptedVerifier = new byte[verifier.Length];
                cipher.Update(verifier, 0, verifier.Length, encryptedVerifier);
                ver.SetEncryptedVerifier(encryptedVerifier);
                HashAlgorithm hashAlgo              = ver.HashAlgorithm;
                MessageDigest hashAlg               = CryptoFunctions.GetMessageDigest(hashAlgo);
                byte[]        calcVerifierHash      = hashAlg.Digest(verifier);
                byte[]        encryptedVerifierHash = cipher.DoFinal(calcVerifierHash);
                ver.SetEncryptedVerifierHash(encryptedVerifierHash);
            }
            catch (Exception e)
            {
                throw new EncryptedDocumentException("Password Confirmation failed", e);
            }
        }
Example #4
0
        public override bool VerifyPassword(String password)
        {
            EncryptionVerifier ver    = builder.GetVerifier();
            ISecretKey         skey   = GenerateSecretKey(password, ver, GetKeySizeInBytes());
            Cipher             cipher = GetCipher(skey);

            try {
                byte[] encryptedVerifier = ver.EncryptedVerifier;
                byte[] verifier          = cipher.DoFinal(encryptedVerifier);
                SetVerifier(verifier);
                MessageDigest sha1                  = CryptoFunctions.GetMessageDigest(ver.HashAlgorithm);
                byte[]        calcVerifierHash      = sha1.Digest(verifier);
                byte[]        encryptedVerifierHash = ver.EncryptedVerifierHash;
                byte[]        decryptedVerifierHash = cipher.DoFinal(encryptedVerifierHash);

                // see 2.3.4.9 Password Verification (Standard Encryption)
                // ... The number of bytes used by the encrypted Verifier hash MUST be 32 ...
                // TODO: check and Trim/pad the hashes to 32
                byte[] verifierHash = Arrays.CopyOf(decryptedVerifierHash, calcVerifierHash.Length);

                if (Arrays.Equals(calcVerifierHash, verifierHash))
                {
                    SetSecretKey(skey);
                    return(true);
                }
                else
                {
                    return(false);
                }
            } catch (Exception e) {
                throw new EncryptedDocumentException(e);
            }
        }
Example #5
0
        public async Task Setup()
        {
            if (secretKey == null)
            {
                var(requestData, abonentNonce) =
                    _builder.BuildStepOne(SharedKey,
                                          Id,
                                          KeyServiceId,
                                          AuthorityId,
                                          Attributes);

                var requestContent = new ByteArrayContent(requestData);
                var client         = new HttpClient();
                var response       = await client.PostAsync(KeyServiceUrl, requestContent);

                var responseData = await response.Content.ReadAsByteArrayAsync();

                var payload = _builder.GetPayload <KeyDistributionAuthToAbonent>(responseData, SharedKey);

                secretKey       = new MockSecretKey();
                secretKey.Value = new byte[payload.SecretKey.Length];
                payload.SecretKey.CopyTo(secretKey.Value, 0);

                publicKey       = new MockPublicKey();
                publicKey.Value = new byte[payload.PublicKey.Length];
                payload.PublicKey.CopyTo(publicKey.Value, 0);
            }
        }
Example #6
0
 public AgileCipherOutputStream(DirectoryNode dir, IEncryptionInfoBuilder builder, ISecretKey skey, AgileEncryptor encryptor)
     : base(dir, 4096, builder, encryptor)
 {
     this.builder   = builder;
     this.skey      = skey;
     this.encryptor = encryptor;
 }
Example #7
0
        private static byte[] TransfromData(ISecretKey key, byte[] source, bool encrpty)
        {
            TkDebug.AssertArgumentNull(key, "key", null);
            TkDebug.AssertArgumentNull(source, "source", null);

            RijndaelManaged managed = new RijndaelManaged();

            using (managed)
            {
                SecretKey secretKey = key as SecretKey;
                if (secretKey != null)
                {
                    managed.Mode    = secretKey.Mode;
                    managed.Padding = secretKey.Padding;
                }
                ICryptoTransform transform;
                if (encrpty)
                {
                    transform = managed.CreateEncryptor(GetHashKey(key.Key), key.IV);
                }
                else
                {
                    transform = managed.CreateDecryptor(GetHashKey(key.Key), key.IV);
                }

                using (transform)
                {
                    return(transform.TransformFinalBlock(source, 0, source.Length));
                }
            }
        }
Example #8
0
        /**
         * Fills the fields of verifier and header with the calculated hashes based
         * on the password and a random salt
         *
         * see [MS-OFFCRYPTO] - 2.3.4.7 ECMA-376 Document Encryption Key Generation
         */
        public override void ConfirmPassword(String password, byte[] keySpec, byte[] keySalt, byte[] verifier, byte[] verifierSalt, byte[] integritySalt)
        {
            StandardEncryptionVerifier ver = builder.GetVerifier();

            ver.SetSalt(verifierSalt);
            ISecretKey secretKey = StandardDecryptor.GenerateSecretKey(password, ver, GetKeySizeInBytes());

            SetSecretKey(secretKey);
            Cipher cipher = GetCipher(secretKey, null);

            try
            {
                byte[]        encryptedVerifier = cipher.DoFinal(verifier);
                MessageDigest hashAlgo          = CryptoFunctions.GetMessageDigest(ver.HashAlgorithm);
                byte[]        calcVerifierHash  = hashAlgo.Digest(verifier);

                // 2.3.3 EncryptionVerifier ...
                // An array of bytes that Contains the encrypted form of the
                // hash of the randomly generated Verifier value. The length of the array MUST be the size of
                // the encryption block size multiplied by the number of blocks needed to encrypt the hash of the
                // Verifier. If the encryption algorithm is RC4, the length MUST be 20 bytes. If the encryption
                // algorithm is AES, the length MUST be 32 bytes. After decrypting the EncryptedVerifierHash
                // field, only the first VerifierHashSize bytes MUST be used.
                int    encVerHashSize        = ver.CipherAlgorithm.encryptedVerifierHashLength;
                byte[] encryptedVerifierHash = cipher.DoFinal(Arrays.CopyOf(calcVerifierHash, encVerHashSize));

                ver.SetEncryptedVerifier(encryptedVerifier);
                ver.SetEncryptedVerifierHash(encryptedVerifierHash);
            }
            catch (Exception e)
            {
                throw new EncryptedDocumentException("Password Confirmation failed", e);
            }
        }
Example #9
0
        public byte[] Decrypt(byte[] data)
        {
            if (data == null || data.Length < initializationVectorLen)
            {
                return(null);
            }

            ISecretKey key = GetKey();

            if (key == null)
            {
                return(null);
            }

            byte[] iv = new byte[initializationVectorLen];
            Buffer.BlockCopy(data, 0, iv, 0, initializationVectorLen);

            Cipher cipher;

            try
            {
                cipher = Cipher.GetInstance(cipherTransformation);
                cipher.Init(CipherMode.DecryptMode, key, new GCMParameterSpec(128, iv));
            }
            catch (InvalidAlgorithmParameterException)
            {
                cipher = Cipher.GetInstance(cipherTransformation);
                cipher.Init(CipherMode.DecryptMode, key, new IvParameterSpec(iv));
            }

            return(cipher.DoFinal(data, initializationVectorLen, data.Length - initializationVectorLen));
        }
Example #10
0
        public override bool VerifyPassword(String password)
        {
            EncryptionVerifier ver  = builder.GetVerifier();
            ISecretKey         skey = GenerateSecretKey(password, ver);

            try {
                Cipher cipher            = InitCipherForBlock(null, 0, builder, skey, Cipher.DECRYPT_MODE);
                byte[] encryptedVerifier = ver.EncryptedVerifier;
                byte[] verifier          = new byte[encryptedVerifier.Length];
                cipher.Update(encryptedVerifier, 0, encryptedVerifier.Length, verifier);
                SetVerifier(verifier);
                byte[]        encryptedVerifierHash = ver.EncryptedVerifierHash;
                byte[]        verifierHash          = cipher.DoFinal(encryptedVerifierHash);
                HashAlgorithm hashAlgo         = ver.HashAlgorithm;
                MessageDigest hashAlg          = CryptoFunctions.GetMessageDigest(hashAlgo);
                byte[]        calcVerifierHash = hashAlg.Digest(verifier);
                if (Arrays.Equals(calcVerifierHash, verifierHash))
                {
                    SetSecretKey(skey);
                    return(true);
                }
            } catch (Exception e) {
                throw new EncryptedDocumentException(e);
            }
            return(false);
        }
Example #11
0
        ISecretKey GetKey()
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.M)
            {
                return(null);
            }

            IKey existingKey = keyStore.GetKey(alias, null);

            if (existingKey != null)
            {
                ISecretKey existingSecretKey = existingKey.JavaCast <ISecretKey>();
                return(existingSecretKey);
            }

            var keyGenerator = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, androidKeyStore);
            var builder      = new KeyGenParameterSpec.Builder(alias, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
                               .SetBlockModes(KeyProperties.BlockModeGcm)
                               .SetEncryptionPaddings(KeyProperties.EncryptionPaddingNone)
                               .SetRandomizedEncryptionRequired(false);

            keyGenerator.Init(builder.Build());

            return(keyGenerator.GenerateKey());
        }
Example #12
0
        public static string DecodeBase64AndDecrypt(
            string alias,
            string cipherText)
        {
            byte[] full        = Convert.FromBase64String(cipherText);
            byte[] iv          = new byte[16];
            byte[] cipherBytes = new byte[full.Length - 16];
            Array.Copy(full, iv, iv.Length);
            Array.Copy(full, 16, cipherBytes, 0, cipherBytes.Length);
            KeyStore keyStore = KeyStore.GetInstance("AndroidKeyStore");

            keyStore.Load(null);
            Cipher          cipher = Cipher.GetInstance("AES/CBC/PKCS7Padding");
            IvParameterSpec spec   = new IvParameterSpec(iv);
            ISecretKey      key    = GetSecretKey(keyStore, alias);

            if (key != null)
            {
                cipher.Init(CipherMode.DecryptMode, key, spec);
                byte[] plainTextBytes = cipher.DoFinal(cipherBytes);
                string plainText      = System.Text.Encoding.UTF8.GetString(plainTextBytes);
                return(plainText);
            }
            else
            {
                return(String.Empty);
            }
        }
Example #13
0
        public static string Encrypt(ISecretKey key, string source)
        {
            TkDebug.AssertArgumentNullOrEmpty(source, "source", null);

            byte[] sourceData = Encoding.UTF8.GetBytes(source);
            byte[] result     = Encrypt(key, sourceData);
            return(Convert.ToBase64String(result));
        }
Example #14
0
 protected Encryption(ISecretKey secretKey, IUtilityKey utilityKey, IEncryptBehavior encryptBiavior,
                      IDecryptBehavior decryptBiavior)
 {
     SecretKey       = secretKey;
     UtilityKey      = utilityKey;
     _encryptBiavior = encryptBiavior;
     _decryptBiavior = decryptBiavior;
 }
Example #15
0
        public static string Decrypt(ISecretKey key, string source)
        {
            TkDebug.AssertArgumentNullOrEmpty(source, "source", null);

            byte[] srcData = Convert.FromBase64String(source);
            byte[] result  = Decrypt(key, srcData);
            return(Encoding.UTF8.GetString(result));
        }
Example #16
0
        private Cipher GetCipher(ISecretKey key)
        {
            EncryptionHeader em = builder.GetHeader();
            ChainingMode     cm = em.ChainingMode;

            Debug.Assert(cm == ChainingMode.ecb);

            return(CryptoFunctions.GetCipher(key, em.CipherAlgorithm, cm, null, Cipher.DECRYPT_MODE));
        }
        public void Add(string key, string value)
        {
            PBEKeySpec       keyspec = new PBEKeySpec(value.ToCharArray());
            SecretKeyFactory fk      = SecretKeyFactory.GetInstance("PBEWithMD5andDES");
            ISecretKey       mysec   = fk.GenerateSecret(keyspec);

            KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(mysec);

            keyStore.SetEntry(key, entry, Password);
            Save();
        }
Example #18
0
        private async Task <byte[]> CreateAndStoreEncryptionKeyLockedAsync(string keyName)
        {
            byte[] keyBytes = null;

            KeyGenerator keyGenerator = KeyGenerator.GetInstance("AES");

            keyGenerator.Init(256, new SecureRandom());
            ISecretKey key = keyGenerator.GenerateKey();

            await StoreKeyAsync(keyName, key).ConfigureAwait(false);

            keyBytes = key.GetEncoded();

            return(keyBytes);
        }
        public void Encryption(object sender, EventArgs eventArgs)
        {
            _secretKey = GenerateKey();
            if (ValidateInput(_activity.textInput.Text))
            {
                return;
            }

            _encipher = GetInstance(Constants.Transformation);
            _encipher.Init(EncryptMode, _secretKey, GenerateGcmParameterSpec());

            byte[]
            results = _encipher.DoFinal(UTF8.GetBytes(_activity.textInput.Text));
            _activity.textOutput.Text = EncodeToString(results, Base64.Default);
        }
Example #20
0
        private static ISecretKey GetSecretKey(
            KeyStore keyStore,
            string alias)
        {
            SecretKeyEntry entry = (SecretKeyEntry)keyStore.GetEntry(alias, null);

            if (entry != null)
            {
                ISecretKey secretKey = entry.SecretKey;
                return(secretKey);
            }
            else
            {
                return(null);
            }
        }
Example #21
0
 public AESObfuscator(byte[] salt, string password)
 {
     try {
         SecretKeyFactory factory = SecretKeyFactory.GetInstance(KEYGEN_ALGORITHM);
         PBEKeySpec       keySpec =
             new PBEKeySpec(password.ToCharArray(), salt, 1024, 256);
         ISecretKey tmp    = factory.GenerateSecret(keySpec);
         ISecretKey secret = new SecretKeySpec(tmp.GetEncoded(), "AES");
         mEncryptor = Cipher.GetInstance(CIPHER_ALGORITHM);
         mEncryptor.Init(Cipher.EncryptMode, secret, new IvParameterSpec(IV));
         mDecryptor = Cipher.GetInstance(CIPHER_ALGORITHM);
         mDecryptor.Init(Cipher.DecryptMode, secret, new IvParameterSpec(IV));
     } catch (GeneralSecurityException e) {
         // This can't happen on a compatible Android device.
         throw new RuntimeException("Invalid environment", e);
     }
 }
Example #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AesObfuscator"/> class.
 /// The aes obfuscator.
 /// </summary>
 /// <param name="salt">
 /// an array of random bytes to use for each (un)obfuscation
 /// </param>
 /// <param name="applicationId">
 /// application identifier, e.g. the package name
 /// </param>
 /// <param name="deviceId">
 /// device identifier. Use as many sources as possible to
 /// create this unique identifier.
 /// </param>
 public AesObfuscator(byte[] salt, string applicationId, string deviceId)
 {
     try
     {
         SecretKeyFactory factory = SecretKeyFactory.GetInstance(KeygenAlgorithm);
         IKeySpec         keySpec = new PBEKeySpec((applicationId + deviceId).ToCharArray(), salt, 1024, 256);
         ISecretKey       tmp     = factory.GenerateSecret(keySpec);
         ISecretKey       secret  = new SecretKeySpec(tmp.GetEncoded(), "AES");
         this.encryptor = Cipher.GetInstance(CipherAlgorithm);
         this.encryptor.Init(CipherMode.EncryptMode, secret, new IvParameterSpec(Iv));
         this.decryptor = Cipher.GetInstance(CipherAlgorithm);
         this.decryptor.Init(CipherMode.DecryptMode, secret, new IvParameterSpec(Iv));
     }
     catch (GeneralSecurityException e)
     {
         // This can't happen on a compatible Android device.
         throw new RuntimeException("Invalid environment", e);
     }
 }
Example #23
0
        private async Task StoreKeyAsync(string keyName, ISecretKey key)
        {
            char[]   deviceId = GetDeviceId().ToCharArray();
            KeyStore keyStore = await GetOrCreateKeyStoreAsync(deviceId).ConfigureAwait(false);

            KeyStore.IProtectionParameter protectionParameter = new KeyStore.PasswordProtection(deviceId);

            // Create the SecretKeyEntry wrapper around the SecretKey
            KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(key);

            // Store the SecretKeyEntry in the KeyStore
            keyStore.SetEntry(keyName, secretKeyEntry, protectionParameter);

            // Write the KeyStore to the app's directory with appropriate permissions
            // Note: we're using the same key to protect the KeyStore as we are to protect the entry inside it.
            using (Stream fileStream = await OpenKeyStoreFileForOutputAsync().ConfigureAwait(false))
            {
                keyStore.Store(fileStream, deviceId);
            }
        }
Example #24
0
        private static byte[] Mac_3des(ISecretKey key, byte[] text, int offset, int length, byte[] iv)
        {
            if (length == -1)
            {
                length = text.Length - offset;
            }

            try
            {
                //Cipher cipher = Cipher.getInstance(DES3_CBC_CIPHER);
                //cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
                //byte[] res = cipher.doFinal(text, offset, length);
                byte[] res = GPCrypto.DoEncrypt_DES3_CBC(key.GetEncoded(), text, offset, length, iv);

                byte[] result = new byte[8];
                Array.Copy(res, res.Length - 8, result, 0, 8);
                return(result);
            }
            catch (Exception e)
            {
                throw new Exception("MAC computation failed.", e);
            }
        }
Example #25
0
        public byte[] Encrypt(byte[] data)
        {
            ISecretKey key = GetKey();

            if (key == null || data == null)
            {
                return(null);
            }

            byte[] iv = new byte[initializationVectorLen];

            SecureRandom sr = new SecureRandom();

            sr.NextBytes(iv);

            Cipher cipher;

            try
            {
                cipher = Cipher.GetInstance(cipherTransformation);
                cipher.Init(CipherMode.EncryptMode, key, new GCMParameterSpec(128, iv));
            }
            catch (InvalidAlgorithmParameterException)
            {
                cipher = Cipher.GetInstance(cipherTransformation);
                cipher.Init(CipherMode.EncryptMode, key, new IvParameterSpec(iv));
            }

            byte[] encryptedBytes = cipher.DoFinal(data);

            byte[] r = new byte[iv.Length + encryptedBytes.Length];
            Buffer.BlockCopy(iv, 0, r, 0, iv.Length);
            Buffer.BlockCopy(encryptedBytes, 0, r, iv.Length, encryptedBytes.Length);

            return(r);
        }
Example #26
0
        protected internal static Cipher InitCipherForBlock(Cipher cipher, int block,
                                                            IEncryptionInfoBuilder builder, ISecretKey skey, int encryptMode)
        {
            EncryptionVerifier ver      = builder.GetVerifier();
            HashAlgorithm      hashAlgo = ver.HashAlgorithm;

            byte[] blockKey = new byte[4];
            LittleEndian.PutUInt(blockKey, 0, block);
            MessageDigest hashAlg = CryptoFunctions.GetMessageDigest(hashAlgo);

            hashAlg.Update(skey.GetEncoded());
            byte[]           encKey = hashAlg.Digest(blockKey);
            EncryptionHeader header = builder.GetHeader();
            int keyBits             = header.KeySize;

            encKey = CryptoFunctions.GetBlock0(encKey, keyBits / 8);
            if (keyBits == 40)
            {
                encKey = CryptoFunctions.GetBlock0(encKey, 16);
            }
            ISecretKey key = new SecretKeySpec(encKey, skey.GetAlgorithm());

            if (cipher == null)
            {
                cipher = CryptoFunctions.GetCipher(key, header.CipherAlgorithm, null, null, encryptMode);
            }
            else
            {
                cipher.Init(encryptMode, key);
            }
            return(cipher);
        }
Example #27
0
        protected internal static Cipher InitCipherForBlock(Cipher existing, int block, bool lastChunk,
                                                            IEncryptionInfoBuilder builder, ISecretKey skey, int encryptionMode)
        {
            EncryptionHeader header = builder.GetHeader();

            if (existing == null || lastChunk)
            {
                String pAdding = (lastChunk ? "PKCS5PAdding" : "NoPAdding");
                existing = CryptoFunctions.GetCipher(skey, header.CipherAlgorithm, header.ChainingMode, header.KeySalt, encryptionMode, pAdding);
            }

            byte[] blockKey = new byte[4];
            LittleEndian.PutInt(blockKey, 0, block);
            byte[] iv = CryptoFunctions.GenerateIv(header.HashAlgorithm, header.KeySalt, blockKey, header.BlockSize);

            AlgorithmParameterSpec aps;

            if (header.CipherAlgorithm == CipherAlgorithm.rc2)
            {
                aps = new RC2ParameterSpec(skey.GetEncoded().Length * 8, iv);
            }
            else
            {
                aps = new IvParameterSpec(iv);
            }

            existing.Init(encryptionMode, skey, aps);
            return(existing);
        }
Example #28
0
 protected void SetSecretKey(ISecretKey secretKey)
 {
     this.secretKey = secretKey;
 }
Example #29
0
 public static Cipher GetCipher(ISecretKey key, CipherAlgorithm cipherAlgorithm, ChainingMode chain, byte[] vec, int cipherMode)
 {
     return(GetCipher(key, cipherAlgorithm, chain, vec, cipherMode, null));
 }
Example #30
0
 public void Init(ISecretKey secretKey)
 {
     throw new NotImplementedException();
 }