public CryptoDevTransform(SymmetricAlgorithm algo, Cipher cipher, bool encryption, byte[] rgbKey, byte[] rgbIV, int bufferBlockSize)
            : base(algo, encryption, rgbKey, rgbIV)
        {
            if (!Helper.IsAvailable (cipher))
                throw new CryptographicException (String.Format ("{0} not available from /dev/crypto", algo));

            // linux does not requires cloning the file descriptor with CRIOGET
            Session sess = new Session ();
            sess.cipher = cipher;
            sess.keylen = (uint) rgbKey.Length;
            fixed (byte* k = &rgbKey [0]) {
                sess.key = (IntPtr) k;
                try {
                    if (Helper.SessionOp (ref sess) < 0)
                        throw new CryptographicException (Marshal.GetLastWin32Error ());
                }
                finally {
                    sess.key = IntPtr.Zero;
                }
            }

            context.ses = sess.ses;
            context.op = encryption ? CryptoOperation.Encrypt : CryptoOperation.Decrypt;
            // CryptoOperation constants differs in OCF (0 is None, ...)
            if (Helper.Mode == KernelMode.Ocf)
                context.op++;

            if (algo.Mode != CipherMode.ECB) {
                save_iv = new byte [BlockSizeByte];
            }

            // change this value if the driver (e.g. mv_cesa) has a limit that
            // it can process in a single shot (e.g. 1936 for AES)
            BufferBlockSize = bufferBlockSize;
        }
Exemple #2
0
        public Cipher ToCipher(Cipher existingFolder)
        {
            existingFolder.Data = JsonConvert.SerializeObject(new FolderDataModel(this), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
            existingFolder.Type = Core.Enums.CipherType.Folder;

            return existingFolder;
        }
Exemple #3
0
        public async Task DeleteAsync(Cipher cipher)
        {
            await _cipherRepository.DeleteAsync(cipher);

            // push
            await _pushService.PushSyncCipherDeleteAsync(cipher);
        }
Exemple #4
0
        public SiteResponseModel(Cipher cipher)
            : base("site")
        {
            if(cipher == null)
            {
                throw new ArgumentNullException(nameof(cipher));
            }

            if(cipher.Type != Core.Enums.CipherType.Site)
            {
                throw new ArgumentException(nameof(cipher.Type));
            }

            var data = new SiteDataModel(cipher);

            Id = cipher.Id.ToString();
            FolderId = cipher.FolderId?.ToString();
            Favorite = cipher.Favorite;
            Name = data.Name;
            Uri = data.Uri;
            Username = data.Username;
            Password = data.Password;
            Notes = data.Notes;
            RevisionDate = cipher.RevisionDate;
        }
        public CipherResponseModel(Cipher cipher)
            : base("cipher")
        {
            if(cipher == null)
            {
                throw new ArgumentNullException(nameof(cipher));
            }

            Id = cipher.Id.ToString();
            FolderId = cipher.FolderId?.ToString();
            Type = cipher.Type;
            Favorite = cipher.Favorite;
            RevisionDate = cipher.RevisionDate;

            switch(cipher.Type)
            {
                case Core.Enums.CipherType.Folder:
                    Data = new FolderDataModel(cipher);
                    break;
                case Core.Enums.CipherType.Site:
                    Data = new SiteDataModel(cipher);
                    break;
                default:
                    throw new ArgumentException("Unsupported " + nameof(Type) + ".");
            }
        }
Exemple #6
0
 /// <summary>
 /// Overrides Close()
 /// </summary>
 /// <param name="cipher"></param>
 /// <param name="rnd"></param>
 /// <param name="mac"></param>
 /// <param name="sequence"></param>
 /// <returns></returns>
 public override DataFragment Close(Cipher cipher, Random rnd, MAC mac, int sequence) {
     byte[] buf = DataWriter.UnderlyingBuffer;
     int sftpDataLength = DataWriter.Length - OFFSET_SFTP_PACKET_TYPE;
     SSHUtil.WriteIntToByteArray(buf, OFFSET_CHANNEL_DATA_LENGTH, sftpDataLength + 4);
     SSHUtil.WriteIntToByteArray(buf, OFFSET_SFTP_DATA_LENGTH, sftpDataLength);
     return base.Close(cipher, rnd, mac, sequence);
 }
Exemple #7
0
        public void Close(Cipher cipher, Random rnd, MAC mac, int sequence, DataFragment result) {
            if(!_is_open) throw new SSHException("internal state error");
            
            int blocksize = cipher==null? 8 : cipher.BlockSize;
            int payload_length = _writer.Length - (SEQUENCE_MARGIN + LENGTH_MARGIN + PADDING_MARGIN);
            int r = 11 - payload_length % blocksize;
            while(r < 4) r += blocksize;
            _paddingLength = r;
            _packetLength = PADDING_MARGIN + payload_length + _paddingLength;
            int image_length = _packetLength + LENGTH_MARGIN;

            //fill padding
            for(int i=0; i<_paddingLength; i+=4)
                _writer.Write(rnd.Next());

            //manipulate stream
            byte[] rawbuf = _writer.UnderlyingBuffer;
            SSHUtil.WriteIntToByteArray(rawbuf, 0, sequence);
            SSHUtil.WriteIntToByteArray(rawbuf, SEQUENCE_MARGIN, _packetLength);
            rawbuf[SEQUENCE_MARGIN + LENGTH_MARGIN] = (byte)_paddingLength;

            //mac
            if(mac!=null) {
                _mac = mac.ComputeHash(rawbuf, 0, _packetLength+LENGTH_MARGIN+SEQUENCE_MARGIN);
                Array.Copy(_mac, 0, rawbuf, _packetLength+LENGTH_MARGIN+SEQUENCE_MARGIN, _mac.Length);
                image_length += _mac.Length;
            }

            //encrypt
            if(cipher!=null)
                cipher.Encrypt(rawbuf, SEQUENCE_MARGIN, _packetLength+LENGTH_MARGIN, rawbuf, SEQUENCE_MARGIN);

            result.Init(rawbuf, SEQUENCE_MARGIN, image_length);
            _is_open = false;
        }
Exemple #8
0
        public static void EnsureAvailability(Cipher cipher)
        {
            EnsureAvailability();

            if (!Crimson.CryptoDev.Helper.IsAvailable (cipher)) {
                Assert.Ignore (string.Format("{0} not available on this platform", cipher));
            }
        }
Exemple #9
0
        public Cipher ToCipher(Cipher existingSite)
        {
            existingSite.FolderId = string.IsNullOrWhiteSpace(FolderId) ? null : (Guid?)new Guid(FolderId);
            existingSite.Favorite = Favorite;
            existingSite.Data = JsonConvert.SerializeObject(new SiteDataModel(this), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
            existingSite.Type = Core.Enums.CipherType.Site;

            return existingSite;
        }
Exemple #10
0
        /// <summary>
        /// Creates a new instance of <see cref="CipherHelper"/>
        /// </summary>
        /// <param name="currentGameVersion">The current MapleStory version</param>
        /// <param name="AESKey">AESKey for the current MapleStory version</param>
        /// <param name="initialBufferSize">Sets the initial size of the buffer</param>
        public CipherHelper(UInt16 currentGameVersion, UInt64 AESKey, UInt16 initialBufferSize = 0x100)
        {
            RecvCipher = new Cipher(currentGameVersion, AESKey);
            SendCipher = new Cipher(currentGameVersion, AESKey);

            DataBuffer = new byte[initialBufferSize];
            AvailableData = 0;
            WaitForData = 0;
            IsWaiting = true;
        }
Exemple #11
0
        public CryptoDevTransform(SymmetricAlgorithm algo, Cipher cipher, bool encryption, byte[] rgbKey, byte[] rgbIV, int bufferBlockSize)
        {
            if (!Helper.IsAvailable (cipher))
                throw new CryptographicException (String.Format ("{0} not available from /dev/crypto", algo));

            if (rgbKey == null)
                throw new CryptographicException ("Invalid (null) key");

            BlockSizeByte = (algo.BlockSize >> 3);

            if (rgbIV == null) {
                rgbIV = KeyBuilder.IV (BlockSizeByte);
            } else {
                // compare the IV length with the "currently selected" block size and *ignore* IV that are too big
                if (rgbIV.Length < BlockSizeByte) {
                    string msg = Locale.GetText ("IV is too small ({0} bytes), it should be {1} bytes long.",
                        rgbIV.Length, BlockSizeByte);
                    throw new CryptographicException (msg);
                }
                rgbIV = (byte[]) rgbIV.Clone ();
            }

            encrypt = encryption;
            padding = algo.Padding;

            // linux does not requires cloning the file descriptor with CRIOGET
            Session sess = new Session ();
            sess.cipher = cipher;
            sess.keylen = (uint) rgbKey.Length;
            fixed (byte* k = &rgbKey [0])
                sess.key = (IntPtr) k;

            if (Helper.SessionOp (ref sess) < 0)
                throw new CryptographicException (Marshal.GetLastWin32Error ());

            context.ses = sess.ses;
            context.op = encryption ? CryptoOperation.Encrypt : CryptoOperation.Decrypt;
            // CryptoOperation constants differs in OCF (0 is None, ...)
            if (Helper.Mode == KernelMode.Ocf)
                context.op++;

            if (algo.Mode != CipherMode.ECB) {
                iv = rgbIV;
                save_iv = new byte [BlockSizeByte];
                fixed (byte* i = &iv [0])
                    context.iv = (IntPtr) i;
            }

            // transform buffer
            workBuff = new byte [BlockSizeByte];
            // change this value if the driver (e.g. mv_cesa) has a limit that
            // it can process in a single shot (e.g. 1936 for AES)
            BufferBlockSize = bufferBlockSize;
        }
Exemple #12
0
        public FolderDataModel(Cipher cipher)
        {
            if(cipher.Type != Core.Enums.CipherType.Folder)
            {
                throw new ArgumentException("Cipher is not correct type.");
            }

            var data = JsonConvert.DeserializeObject<FolderDataModel>(cipher.Data);

            Name = data.Name;
        }
Exemple #13
0
 public static byte[] Decrypt(byte[]data, Cipher cipher, byte[] key)
 {
     switch (cipher)
     {
         case Cipher.Aes128CbcWithGzip:
             return DecryptAes128CbcWithGzip(data, key);
         case Cipher.Aes128Ecb:
             return DecryptAes128Ecb(data, key);
         default:
             throw new NotSupportedException();
     }
 }
        /// <summary>
        /// Entry Point for the Challenge
        /// </summary>
        /// <param name="args">Command line Arguments</param>
        public static void Main(string[] args)
        {
            Cipher c = new Cipher();
            foreach (var line in File.ReadLines(args[0]))
            {
                var split = line.Split(';');

                var key = new byte[split[0].Length];
                for (int i = 0; i < key.Length; i++) { key[i] = (byte)(split[0][i] - '0'); }

                Console.WriteLine(c.Decode(split[1], key));
            }
        }
 public async Task PushSyncCipherDeleteAsync(Cipher cipher)
 {
     switch(cipher.Type)
     {
         case CipherType.Folder:
             await PushCipherAsync(cipher, PushType.SyncFolderDelete);
             break;
         case CipherType.Site:
             await PushCipherAsync(cipher, PushType.SyncSiteDelete);
             break;
         default:
             break;
     }
 }
Exemple #16
0
        public SiteDataModel(Cipher cipher)
        {
            if(cipher.Type != Core.Enums.CipherType.Site)
            {
                throw new ArgumentException("Cipher is not correct type.");
            }

            var data = JsonConvert.DeserializeObject<SiteDataModel>(cipher.Data);

            Name = data.Name;
            Uri = data.Uri;
            Username = data.Username;
            Password = data.Password;
            Notes = data.Notes;
        }
 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);
     }
 }
Exemple #18
0
        public HashHelper(Cipher algo)
        {
            if (!Helper.IsAvailable (algo))
                throw new CryptographicException (String.Format ("{0} not available from /dev/crypto", algo));

            // linux does not requires cloning the file descriptor with CRIOGET
            Session sess = new Session ();
            sess.mac = algo;

            if (Helper.SessionOp (ref sess) < 0)
                throw new CryptographicException (Marshal.GetLastWin32Error ());

            context.ses = sess.ses;
            context.op = CryptoOperation.Encrypt;
            // change this value if the driver (e.g. mv_cesa) has a limit that
            // it can process in a single shot (e.g. 1932 for SHA1)
            BufferBlockSize = Int32.MaxValue;
        }
Exemple #19
0
        public async Task SaveAsync(Cipher cipher)
        {
            if(cipher.Id == default(Guid))
            {
                await _cipherRepository.CreateAsync(cipher);

                // push
                await _pushService.PushSyncCipherCreateAsync(cipher);
            }
            else
            {
                cipher.RevisionDate = DateTime.UtcNow;
                await _cipherRepository.ReplaceAsync(cipher);

                // push
                await _pushService.PushSyncCipherUpdateAsync(cipher);
            }
        }
Exemple #20
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 public MainForm()
 {
     String key;
     using (AccessForm access = new AccessForm())
     {
         if (access.ShowDialog() != DialogResult.OK)
         {
             Environment.Exit(0);
         }
         key = access.keyTextBox.Text;
     }
     if (String.IsNullOrEmpty(key))
     {
         MessageBox.Show("Wrong key!", "Password Keeper", MessageBoxButtons.OK, MessageBoxIcon.Warning);
         Environment.Exit(0);
     }
     if (!Directory.Exists(ConfigurationPath))
     {
         CreateDirectory(ConfigurationPath);
     }
     if (File.Exists(keyFile))
     {
         using (Cipher cipher = new Cipher(key))
         {
             if (key != cipher.Decrypt(File.ReadAllText(keyFile)))
             {
                 MessageBox.Show("Wrong key!", "Password Keeper", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                 Environment.Exit(0);
             }
         }
     }
     else
     {
         Stream stream = File.Create(keyFile);
         using (Cipher cipher = new Cipher(key))
         {
             String encrypted = cipher.Encrypt(key);
             stream.Write(Encoding.ASCII.GetBytes(encrypted), 0, encrypted.Length);
         }
     }
     InitializeComponent();
     this.cipher = new Cipher(key);
     key = String.Empty;
 }
Exemple #21
0
        public FolderResponseModel(Cipher cipher)
            : base("folder")
        {
            if(cipher == null)
            {
                throw new ArgumentNullException(nameof(cipher));
            }

            if(cipher.Type != Core.Enums.CipherType.Folder)
            {
                throw new ArgumentException(nameof(cipher.Type));
            }

            var data = new FolderDataModel(cipher);

            Id = cipher.Id.ToString();
            Name = data.Name;
            RevisionDate = cipher.RevisionDate;
        }
        private async Task PushCipherAsync(Cipher cipher, PushType type)
        {
            var message = new SyncCipherPushNotification
            {
                Type = type,
                Id = cipher.Id,
                UserId = cipher.UserId,
                RevisionDate = cipher.RevisionDate,
                Aps = new PushNotification.AppleData { ContentAvailable = 1 }
            };

            var excludedTokens = new List<string>();
            if(!string.IsNullOrWhiteSpace(_currentContext.DeviceIdentifier))
            {
                excludedTokens.Add(_currentContext.DeviceIdentifier);
            }

            await PushToAllUserDevicesAsync(cipher.UserId, JObject.FromObject(message), excludedTokens);
        }
Exemple #23
0
        // Derived class can override this method to modify the buffer.
        public virtual DataFragment Close(Cipher cipher, MAC mac, int sequence) {
            if (!_isOpen)
                throw new SSHException("internal state error");

            int blocksize = cipher == null ? 8 : cipher.BlockSize;
            int payloadLength = _writer.Length - (SEQUENCE_MARGIN + LENGTH_MARGIN + PADDING_MARGIN);
            int paddingLength = 11 - payloadLength % blocksize;
            while (paddingLength < 4)
                paddingLength += blocksize;
            int packetLength = PADDING_MARGIN + payloadLength + paddingLength;
            int imageLength = packetLength + LENGTH_MARGIN;

            //fill padding
	        byte[] tmp = new byte[4];
            Rng rng = RngManager.GetSecureRng();
            for (int i = 0; i < paddingLength; i += 4) {
                rng.GetBytes(tmp);
                _writer.Write(tmp);
            }

            //manipulate stream
            byte[] rawbuf = _writer.UnderlyingBuffer;
            SSHUtil.WriteIntToByteArray(rawbuf, 0, sequence);
            SSHUtil.WriteIntToByteArray(rawbuf, SEQUENCE_MARGIN, packetLength);
            rawbuf[SEQUENCE_MARGIN + LENGTH_MARGIN] = (byte)paddingLength;

            //mac
            if (mac != null) {
                byte[] macCode = mac.ComputeHash(rawbuf, 0, packetLength + LENGTH_MARGIN + SEQUENCE_MARGIN);
                Array.Copy(macCode, 0, rawbuf, packetLength + LENGTH_MARGIN + SEQUENCE_MARGIN, macCode.Length);
                imageLength += macCode.Length;
            }

            //encrypt
            if (cipher != null)
                cipher.Encrypt(rawbuf, SEQUENCE_MARGIN, packetLength + LENGTH_MARGIN, rawbuf, SEQUENCE_MARGIN);

            _dataFragment.Init(rawbuf, SEQUENCE_MARGIN, imageLength);
            _isOpen = false;
            return _dataFragment;
        }
Exemple #24
0
        public virtual Cipher ToCipher(string userId = null)
        {
            var cipher = new Cipher
            {
                Id = new Guid(Id),
                UserId = new Guid(userId),
                FolderId = string.IsNullOrWhiteSpace(FolderId) ? null : (Guid?)new Guid(FolderId),
                Type = Type
            };

            switch(Type)
            {
                case CipherType.Folder:
                    cipher.Data = JsonConvert.SerializeObject(new FolderDataModel(this), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
                    break;
                case CipherType.Site:
                    cipher.Data = JsonConvert.SerializeObject(new SiteDataModel(this), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
                    break;
                default:
                    throw new ArgumentException("Unsupported " + nameof(Type) + ".");
            }

            return cipher;
        }
Exemple #25
0
 public async Task PushSyncCipherDeleteAsync(Cipher cipher)
 {
     await PushCipherAsync(cipher, PushType.SyncLoginDelete);
 }
Exemple #26
0
 /// <summary>
 /// Creates a new instance of Crypto
 /// </summary>
 /// <param name="GameVersion">The current MapleStory version</param>
 public Crypto(ushort GameVersion)
 {
     RecvCipher = new Cipher(GameVersion);
     SendCipher = new Cipher(GameVersion);
 }
Exemple #27
0
 public SSH1PacketBuilder(IDataHandler handler)
     : base(handler)
 {
     _buffer = new byte[0x1000];
     _readOffset = 0;
     _writeOffset = 0;
     _cipher = null;
     _checkMAC = false;
 }
Exemple #28
0
 //init ciphers
 private void InitCipher(byte[] session_key)
 {
     lock (_transmitSync) {
         _cipher = CipherFactory.CreateCipher(SSHProtocol.SSH1, _cInfo.OutgoingPacketCipher.Value, session_key);
         Cipher rc = CipherFactory.CreateCipher(SSHProtocol.SSH1, _cInfo.IncomingPacketCipher.Value, session_key);
         _packetizer.SetCipher(rc, _param.CheckMACError);
     }
 }
        /*
         * Format style note
         *  ---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----
         *  Comment: *******
         *  <base64-encoded body>
         *  ---- END SSH2 ENCRYPTED PRIVATE KEY ----
         *
         *  body = MAGIC_VAL || body-length || type(string) || encryption-algorithm-name(string) || encrypted-body(string)
         *  encrypted-body = array of BigInteger(algorithm-specific)
         */
        public static SSH2UserAuthKey FromSECSHStyleStream(Stream strm, string passphrase)
        {
            StreamReader r = new StreamReader(strm, Encoding.ASCII);
            string       l = r.ReadLine();

            if (l == null || l != "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")
            {
                throw new SSHException("Wrong key format");
            }

            string comment = "";

            l = r.ReadLine();
            StringBuilder buf = new StringBuilder();

            while (l != "---- END SSH2 ENCRYPTED PRIVATE KEY ----")
            {
                if (l.IndexOf(':') == -1)
                {
                    buf.Append(l);
                }
                else if (l[l.Length - 1] == '\\')
                {
                    buf.Append(l, 0, l.Length - 1);
                }
                else if (l.StartsWith("Comment: "))
                {
                    comment = l.Substring("Comment: ".Length);
                }

                l = r.ReadLine();
                if (l == null)
                {
                    throw new SSHException("Key is broken");
                }
            }
            r.Close();

            byte[] keydata = Base64.Decode(Encoding.ASCII.GetBytes(buf.ToString()));
            //Debug.WriteLine(DebugUtil.DumpByteArray(keydata));


            SSH2DataReader re    = new SSH2DataReader(keydata);
            int            magic = re.ReadInt32();

            if (magic != MAGIC_VAL)
            {
                throw new SSHException("key file is broken");
            }
            int    privateKeyLen = re.ReadInt32();
            string type          = Encoding.ASCII.GetString(re.ReadString());

            string ciphername = Encoding.ASCII.GetString(re.ReadString());
            int    bufLen     = re.ReadInt32();

            if (ciphername != "none")
            {
                CipherAlgorithm algo = CipherFactory.SSH2NameToAlgorithm(ciphername);
                byte[]          key  = PassphraseToKey(passphrase, CipherFactory.GetKeySize(algo));
                Cipher          c    = CipherFactory.CreateCipher(SSHProtocol.SSH2, algo, key);
                byte[]          tmp  = new Byte[re.Image.Length - re.Offset];
                c.Decrypt(re.Image, re.Offset, re.Image.Length - re.Offset, tmp, 0);
                re = new SSH2DataReader(tmp);
            }

            int parmLen = re.ReadInt32();

            if (parmLen < 0 || parmLen > re.Rest)
            {
                throw new SSHException(Strings.GetString("WrongPassphrase"));
            }

            if (type.IndexOf("if-modn") != -1)
            {
                //mindterm mistaken this order of BigIntegers
                BigInteger e = re.ReadBigIntWithBits();
                BigInteger d = re.ReadBigIntWithBits();
                BigInteger n = re.ReadBigIntWithBits();
                BigInteger u = re.ReadBigIntWithBits();
                BigInteger p = re.ReadBigIntWithBits();
                BigInteger q = re.ReadBigIntWithBits();
                return(new SSH2UserAuthKey(new RSAKeyPair(e, d, n, u, p, q), comment));
            }
            else if (type.IndexOf("dl-modp") != -1)
            {
                if (re.ReadInt32() != 0)
                {
                    throw new SSHException("DSS Private Key File is broken");
                }
                BigInteger p = re.ReadBigIntWithBits();
                BigInteger g = re.ReadBigIntWithBits();
                BigInteger q = re.ReadBigIntWithBits();
                BigInteger y = re.ReadBigIntWithBits();
                BigInteger x = re.ReadBigIntWithBits();
                return(new SSH2UserAuthKey(new DSAKeyPair(p, g, q, y, x), comment));
            }
            else
            {
                throw new SSHException("unknown authentication method " + type);
            }
        }
Exemple #30
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Commandline Parameter Error");
                Console.WriteLine("Example:  SolveMe_Riddle.exe <Wordfile Filename> <Cipher Filename>");
                Console.WriteLine("Arguments = " + String.Join(';', args));
            }
            else
            {
                var      WordFilename = args[0];
                WordFile theWordfile  = GetWordfile(WordFilename);

                var    CipherFilename = args[1];
                Cipher theCipherFile  = GetCipher(CipherFilename);

                Debug.Print(theCipherFile.GetBytes.Length.ToString());

                if (theWordfile is null)
                {
                    Console.WriteLine("Error loading Wordfile.");
                }
                else if (theCipherFile is null)
                {
                    Console.WriteLine("Error loading CipherFile.");
                }
                else
                {
                    Console.WriteLine("Start Processing...");

                    byte[] nextKeys;
                    var    theKeygen      = new Keygen();
                    var    theDecrypter   = new Decrypter();
                    var    theWordtester  = new WordTester(theWordfile);
                    var    theLogger      = new Logger("Logger.txt");
                    var    DecryptedBytes = new byte[theCipherFile.GetBytes.Length];

                    while (!theKeygen.AllKeysDelivered)
                    {
                        nextKeys       = theKeygen.GetNextKeys();
                        DecryptedBytes = theDecrypter.DecryptBytes(theCipherFile.GetBytes, nextKeys);
                        bool TestText = theWordtester.TestAsciiBytes(DecryptedBytes);

                        if (TestText && theWordtester.LastMatchCollection.Count >= 8)
                        {
                            Console.WriteLine(":)");
                            Console.Write("{0} - Found Key : {1,3} {2,3} {3,3} -> ", DateTime.Now.ToString(), nextKeys[0], nextKeys[1], nextKeys[2]);
                            Console.WriteLine("");
                            Console.WriteLine("Anzahl an Wort Treffer ---> {0}", theWordtester.LastMatchCollection.Count);
                            foreach (Match m in theWordtester.LastMatchCollection)
                            {
                                Console.WriteLine("---> {0}", m.Value);
                            }

                            Console.WriteLine("{0}", theWordtester.LastMatchCollection);

                            Console.WriteLine("");
                            Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(theDecrypter.DecryptedBytes));
                            Console.WriteLine("");
                            Console.WriteLine("");
                        }
                    }
                    Console.WriteLine("Finish.");
                }
            }
        }
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "GetFriends/{myPublicKey}")] HttpRequest req,
            string myPublicKey,
            [Table("Friend")] CloudTable friendTable,
            [Table("User")] CloudTable userTable,
            ILogger log)
        {
            log.LogInformation($"C# HTTP trigger {nameof(SubmitFriendRequest)} function processed a request.");


            var privateKey = Utils.ParseToken(req);

            if (privateKey == null)
            {
                return new HttpResponseMessage(HttpStatusCode.Unauthorized)
                       {
                           Content = new StringContent("You are not authorized to make this request.")
                       }
            }
            ;

            if (string.IsNullOrWhiteSpace(myPublicKey))
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("Invalid data to process request")
                });
            }

            try
            {
                var user = await Utils.FindUserEntitySlim(userTable, privateKey, myPublicKey);

                if (user == null)
                {
                    return new HttpResponseMessage(HttpStatusCode.BadRequest)
                           {
                               Content = new StringContent("Unable to locate your user account.")
                           }
                }
                ;
            }
            catch (Exception ex)
            {
                log.LogInformation("User doesn't exist: " + ex.Message);
                return(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("Unable to locate your user account.")
                });
            }


            var statuses = new List <FriendStatus>();

            try
            {
                var publicKeyFilter = TableQuery.GenerateFilterCondition("PartitionKey",
                                                                         QueryComparisons.Equal, myPublicKey);

                var rangeQuery = new TableQuery <FriendEntity>().Where(publicKeyFilter);

                var friends = await friendTable.ExecuteQuerySegmentedAsync(rangeQuery, null);

                // spin off tasks for finding all friends
                var tasks = new List <Task <TableQuerySegment <UserEntity> > >();
                foreach (var f in friends)
                {
                    tasks.Add(Utils.FindFriendTask(userTable, f.RequesteePublicKey));
                }

                await Task.WhenAll(tasks);

                foreach (var t in tasks)
                {
                    var friend = t.Result?.Results?.FirstOrDefault();
                    if (friend == null)
                    {
                        continue;
                    }

                    var friendCode = string.Empty;
                    try
                    {
                        friendCode = Cipher.Decrypt(friend.FriendCode, Utils.FriendCodePassword, friend.PublicKey);
                    }
                    catch (Exception ex)
                    {
                        log.LogError("Unable to decrypt friendcode: " + ex.Message);
                    }

                    statuses.Add(new FriendStatus
                    {
                        AMPrice               = friend.AMPrice,
                        BuyPrice              = friend.BuyPrice,
                        Fruit                 = friend.Fruit,
                        IslandName            = friend.IslandName,
                        Name                  = friend.Name,
                        PMPrice               = friend.PMPrice,
                        PublicKey             = friend.PublicKey,
                        Status                = friend.Status,
                        TimeZone              = friend.TimeZone,
                        TurnipUpdateDayOfYear = friend.TurnipUpdateDayOfYear,
                        TurnipUpdateTimeUTC   = friend.TurnipUpdateTimeUTC,
                        TurnipUpdateYear      = friend.TurnipUpdateYear,
                        FriendCode            = friendCode,
                        MaxPrediction         = friend.MaxPrediction,
                        MinPrediction         = friend.MinPrediction
                    });
                }
            }
            catch (Exception ex)
            {
                log.LogError($"Error {nameof(GetFriends)} - Error: " + ex.Message);
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }

            var json = JsonConvert.SerializeObject(statuses);

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(json, Encoding.UTF8, "application/json")
            });
        }
    }
Exemple #32
0
        private void InitSave()
        {
            var saveToolBarItem = new ToolbarItem(AppResources.Save, Helpers.ToolbarImage("envelope.png"), async() =>
            {
                if (_lastAction.LastActionWasRecent())
                {
                    return;
                }
                _lastAction = DateTime.UtcNow;

                if (!_connectivity.IsConnected)
                {
                    AlertNoConnection();
                    return;
                }

                if (string.IsNullOrWhiteSpace(NameCell.Entry.Text))
                {
                    await DisplayAlert(AppResources.AnErrorHasOccurred, string.Format(AppResources.ValidationFieldRequired,
                                                                                      AppResources.Name), AppResources.Ok);
                    return;
                }

                var cipher = new Cipher
                {
                    Name     = NameCell.Entry.Text.Encrypt(),
                    Notes    = string.IsNullOrWhiteSpace(NotesCell.Editor.Text) ? null : NotesCell.Editor.Text.Encrypt(),
                    Favorite = FavoriteCell.On,
                    Type     = _type
                };

                switch (_type)
                {
                case CipherType.Login:
                    cipher.Login = new Login
                    {
                        Username = string.IsNullOrWhiteSpace(LoginUsernameCell.Entry.Text) ? null :
                                   LoginUsernameCell.Entry.Text.Encrypt(),
                        Password = string.IsNullOrWhiteSpace(LoginPasswordCell.Entry.Text) ? null :
                                   LoginPasswordCell.Entry.Text.Encrypt(),
                        Totp = string.IsNullOrWhiteSpace(LoginTotpCell.Entry.Text) ? null :
                               LoginTotpCell.Entry.Text.Encrypt(),
                    };

                    Helpers.ProcessUrisSectionForSave(UrisSection, cipher);
                    break;

                case CipherType.SecureNote:
                    cipher.SecureNote = new SecureNote
                    {
                        Type = SecureNoteType.Generic
                    };
                    break;

                case CipherType.Card:
                    string brand;
                    switch (CardBrandCell.Picker.SelectedIndex)
                    {
                    case 1:
                        brand = "Visa";
                        break;

                    case 2:
                        brand = "Mastercard";
                        break;

                    case 3:
                        brand = "Amex";
                        break;

                    case 4:
                        brand = "Discover";
                        break;

                    case 5:
                        brand = "Diners Club";
                        break;

                    case 6:
                        brand = "JCB";
                        break;

                    case 7:
                        brand = "Maestro";
                        break;

                    case 8:
                        brand = "UnionPay";
                        break;

                    case 9:
                        brand = "Other";
                        break;

                    default:
                        brand = null;
                        break;
                    }

                    var expMonth = CardExpMonthCell.Picker.SelectedIndex > 0 ?
                                   CardExpMonthCell.Picker.SelectedIndex.ToString() : null;

                    cipher.Card = new Card
                    {
                        CardholderName = string.IsNullOrWhiteSpace(CardNameCell.Entry.Text) ? null :
                                         CardNameCell.Entry.Text.Encrypt(),
                        Number = string.IsNullOrWhiteSpace(CardNumberCell.Entry.Text) ? null :
                                 CardNumberCell.Entry.Text.Encrypt(),
                        ExpYear = string.IsNullOrWhiteSpace(CardExpYearCell.Entry.Text) ? null :
                                  CardExpYearCell.Entry.Text.Encrypt(),
                        Code = string.IsNullOrWhiteSpace(CardCodeCell.Entry.Text) ? null :
                               CardCodeCell.Entry.Text.Encrypt(),
                        Brand    = string.IsNullOrWhiteSpace(brand) ? null : brand.Encrypt(),
                        ExpMonth = string.IsNullOrWhiteSpace(expMonth) ? null : expMonth.Encrypt(),
                    };
                    break;

                case CipherType.Identity:
                    string title;
                    switch (IdTitleCell.Picker.SelectedIndex)
                    {
                    case 1:
                        title = AppResources.Mr;
                        break;

                    case 2:
                        title = AppResources.Mrs;
                        break;

                    case 3:
                        title = AppResources.Ms;
                        break;

                    case 4:
                        title = AppResources.Dr;
                        break;

                    default:
                        title = null;
                        break;
                    }

                    cipher.Identity = new Identity
                    {
                        Title     = string.IsNullOrWhiteSpace(title) ? null : title.Encrypt(),
                        FirstName = string.IsNullOrWhiteSpace(IdFirstNameCell.Entry.Text) ? null :
                                    IdFirstNameCell.Entry.Text.Encrypt(),
                        MiddleName = string.IsNullOrWhiteSpace(IdMiddleNameCell.Entry.Text) ? null :
                                     IdMiddleNameCell.Entry.Text.Encrypt(),
                        LastName = string.IsNullOrWhiteSpace(IdLastNameCell.Entry.Text) ? null :
                                   IdLastNameCell.Entry.Text.Encrypt(),
                        Username = string.IsNullOrWhiteSpace(IdUsernameCell.Entry.Text) ? null :
                                   IdUsernameCell.Entry.Text.Encrypt(),
                        Company = string.IsNullOrWhiteSpace(IdCompanyCell.Entry.Text) ? null :
                                  IdCompanyCell.Entry.Text.Encrypt(),
                        SSN = string.IsNullOrWhiteSpace(IdSsnCell.Entry.Text) ? null :
                              IdSsnCell.Entry.Text.Encrypt(),
                        PassportNumber = string.IsNullOrWhiteSpace(IdPassportNumberCell.Entry.Text) ? null :
                                         IdPassportNumberCell.Entry.Text.Encrypt(),
                        LicenseNumber = string.IsNullOrWhiteSpace(IdLicenseNumberCell.Entry.Text) ? null :
                                        IdLicenseNumberCell.Entry.Text.Encrypt(),
                        Email = string.IsNullOrWhiteSpace(IdEmailCell.Entry.Text) ? null :
                                IdEmailCell.Entry.Text.Encrypt(),
                        Phone = string.IsNullOrWhiteSpace(IdPhoneCell.Entry.Text) ? null :
                                IdPhoneCell.Entry.Text.Encrypt(),
                        Address1 = string.IsNullOrWhiteSpace(IdAddress1Cell.Entry.Text) ? null :
                                   IdAddress1Cell.Entry.Text.Encrypt(),
                        Address2 = string.IsNullOrWhiteSpace(IdAddress2Cell.Entry.Text) ? null :
                                   IdAddress2Cell.Entry.Text.Encrypt(),
                        Address3 = string.IsNullOrWhiteSpace(IdAddress3Cell.Entry.Text) ? null :
                                   IdAddress3Cell.Entry.Text.Encrypt(),
                        City = string.IsNullOrWhiteSpace(IdCityCell.Entry.Text) ? null :
                               IdCityCell.Entry.Text.Encrypt(),
                        State = string.IsNullOrWhiteSpace(IdStateCell.Entry.Text) ? null :
                                IdStateCell.Entry.Text.Encrypt(),
                        PostalCode = string.IsNullOrWhiteSpace(IdPostalCodeCell.Entry.Text) ? null :
                                     IdPostalCodeCell.Entry.Text.Encrypt(),
                        Country = string.IsNullOrWhiteSpace(IdCountryCell.Entry.Text) ? null :
                                  IdCountryCell.Entry.Text.Encrypt()
                    };
                    break;

                default:
                    break;
                }

                if (FolderCell.Picker.SelectedIndex > 0)
                {
                    cipher.FolderId = Folders.ElementAt(FolderCell.Picker.SelectedIndex - 1).Id;
                }

                Helpers.ProcessFieldsSectionForSave(FieldsSection, cipher);

                await _deviceActionService.ShowLoadingAsync(AppResources.Saving);
                var saveTask = await _cipherService.SaveAsync(cipher);
                await _deviceActionService.HideLoadingAsync();

                if (saveTask.Succeeded)
                {
                    _deviceActionService.Toast(AppResources.NewItemCreated);
                    if (_fromAutofill)
                    {
                        _googleAnalyticsService.TrackExtensionEvent("CreatedCipher");
                    }
                    else
                    {
                        _googleAnalyticsService.TrackAppEvent("CreatedCipher");
                    }

                    if (_fromAutofillFramework)
                    {
                        // close and go back to app
                        _deviceActionService.CloseAutofill();
                    }
                    else
                    {
                        await Navigation.PopForDeviceAsync();
                    }
                }
                else if (saveTask.Errors.Count() > 0)
                {
                    await DisplayAlert(AppResources.AnErrorHasOccurred, saveTask.Errors.First().Message, AppResources.Ok);
                }
                else
                {
                    await DisplayAlert(null, AppResources.AnErrorHasOccurred, AppResources.Ok);
                }
            }, ToolbarItemOrder.Default, 0);

            ToolbarItems.Add(saveToolBarItem);
        }
Exemple #33
0
 public async Task PushSyncCipherUpdateAsync(Cipher cipher)
 {
     await PushCipherAsync(cipher, PushType.SyncCipherUpdate);
 }
 public Task LogCipherEventAsync(Cipher cipher, EventType type, DateTime?date = null)
 {
     return(Task.FromResult(0));
 }
Exemple #35
0
 internal void RefreshKeys(byte[] sessionID, Cipher tc, Cipher rc, MAC tm, MAC rm)
 {
     _sessionID = sessionID;
     _tCipher = tc;
     _tMAC = tm;
     _packetBuilder.SetCipher(rc, _param.CheckMACError? rm : null);
     _asyncKeyExchanger = null;
 }
 public void SetCipher(Cipher c, bool check_mac)
 {
     _cipher   = c;
     _checkMAC = check_mac;
 }
        public void WritePrivatePartInSECSHStyleFile(Stream dest, string comment, string passphrase)
        {
            //step1 key body
            SSH2DataWriter wr = new SSH2DataWriter();

            wr.Write(0);             //this field is filled later
            if (_keypair.Algorithm == PublicKeyAlgorithm.RSA)
            {
                RSAKeyPair   rsa = (RSAKeyPair)_keypair;
                RSAPublicKey pub = (RSAPublicKey)_keypair.PublicKey;
                wr.WriteBigIntWithBits(pub.Exponent);
                wr.WriteBigIntWithBits(rsa.D);
                wr.WriteBigIntWithBits(pub.Modulus);
                wr.WriteBigIntWithBits(rsa.U);
                wr.WriteBigIntWithBits(rsa.P);
                wr.WriteBigIntWithBits(rsa.Q);
            }
            else
            {
                DSAKeyPair   dsa = (DSAKeyPair)_keypair;
                DSAPublicKey pub = (DSAPublicKey)_keypair.PublicKey;
                wr.Write(0);
                wr.WriteBigIntWithBits(pub.P);
                wr.WriteBigIntWithBits(pub.G);
                wr.WriteBigIntWithBits(pub.Q);
                wr.WriteBigIntWithBits(pub.Y);
                wr.WriteBigIntWithBits(dsa.X);
            }

            int padding_len = 0;

            if (passphrase != null)
            {
                padding_len = 8 - (int)wr.Length % 8;
                wr.Write(new byte[padding_len]);
            }
            byte[] encrypted_body = wr.ToByteArray();
            SSHUtil.WriteIntToByteArray(encrypted_body, 0, encrypted_body.Length - padding_len - 4);

            //encrypt if necessary
            if (passphrase != null)
            {
                Cipher c = CipherFactory.CreateCipher(SSHProtocol.SSH2, CipherAlgorithm.TripleDES, PassphraseToKey(passphrase, 24));
                Debug.Assert(encrypted_body.Length % 8 == 0);
                byte[] tmp = new Byte[encrypted_body.Length];
                c.Encrypt(encrypted_body, 0, encrypted_body.Length, tmp, 0);
                encrypted_body = tmp;
            }

            //step2 make binary key data
            wr = new SSH2DataWriter();
            wr.Write(MAGIC_VAL);
            wr.Write(0);             //for total size
            wr.Write(_keypair.Algorithm == PublicKeyAlgorithm.RSA?
                     "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}" :
                     "dl-modp{sign{dsa-nist-sha1},dh{plain}}");

            wr.Write(passphrase == null? "none" : "3des-cbc");
            wr.WriteAsString(encrypted_body);

            byte[] rawdata = wr.ToByteArray();
            SSHUtil.WriteIntToByteArray(rawdata, 4, rawdata.Length);             //fix total length

            //step3 write final data
            StreamWriter sw = new StreamWriter(dest, Encoding.ASCII);

            sw.WriteLine("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----");
            if (comment != null)
            {
                WriteKeyFileBlock(sw, "Comment: " + comment, true);
            }
            WriteKeyFileBlock(sw, Encoding.ASCII.GetString(Base64.Encode(rawdata)), false);
            sw.WriteLine("---- END SSH2 ENCRYPTED PRIVATE KEY ----");
            sw.Close();
        }
 public CipherShareRequest(Cipher cipher)
 {
     Cipher        = new CipherRequest(cipher);
     CollectionIds = cipher.CollectionIds?.ToList();
 }
        public async Task <ActionResult> Decrypt([FromRoute] Guid vuid, [FromRoute] Guid keyId, [FromBody] string data, string token, string sign)
        {
            var msgErr  = $"Denied data decryption belonging to {vuid}";
            var account = await _managerCvk.GetById(vuid);

            var tran = TranToken.Parse(Convert.FromBase64String(token.DecodeBase64Url()));

            if (!tran.Check(account.CvkiAuth))
            {
                _logger.LogInformation("Decryption denied for vuid {0} with keyId {1}: Invalid token.", vuid, keyId);
                return(BadRequest(msgErr));
            }

            var keyPub = await _keyIdManager.GetById(keyId);

            if (keyPub == null)
            {
                _logger.LogInformation("Decryption denied for vuid {0} with keyId {1}: keyId not found.", vuid, keyId);
                return(BadRequest(msgErr));
            }

            var buffers = GetBytes(data);

            if (buffers.Any(bff => !Cipher.CheckAsymmetric(bff, account.CvkPub)))
            {
                _logger.LogInformation("Decryption denied for vuid {0} with keyId {1}: Invalid asymmetric data.", vuid, keyId);
                return(BadRequest(msgErr));
            }

            var tags  = buffers.Select(bff => Cipher.GetTag(bff)).Distinct().ToList();
            var rules = (await _ruleManager.GetSetBy(account.VuId, tags, keyPub.Id)).Where(rl => rl.Eval()).ToList();

            if (!tags.All(tag => rules.Where(rule => tag == rule.Tag).Any(rule => rule.IsAllowed)))
            {
                _logger.LogInformation("Decryption denied for vuid {0} with keyId {1}: No rule to allow decryption. Tags: " + string.Join(' ', tags), vuid, keyId);
                return(BadRequest(msgErr));
            }

            if (tags.Any(tag => rules.Where(rule => tag == rule.Tag).Any(rule => rule.IsDenied)))
            {
                _logger.LogInformation("Decryption denied for vuid {0} with keyId {1}: Denied by rule", vuid, keyId);
                return(BadRequest(msgErr));
            }

            var bufferSign = Convert.FromBase64String(sign.DecodeBase64Url());
            var sessionKey = tran.GenKey(account.CvkiAuth);

            if (!Utils.Equals(sessionKey.Hash(buffers.SelectMany(bff => bff).ToArray()), bufferSign))
            {
                _logger.LogInformation("Decryption denied for vuid {0} with keyId {1}: Invalid symmetric data signature.", vuid, keyId);
                return(BadRequest(msgErr));
            }

            var c1s = buffers.Select(bff => Cipher.GetCipherC1(bff)).ToList();

            if (c1s.Any(c1 => !c1.IsValid))
            {
                _logger.LogInformation("Decryption denied for vuid {0} with keyId {1}: Invalid data point.", vuid, keyId);
                return(BadRequest(msgErr));
            }

            _logger.LogInformation("Decryption granted for vuid {0} with keyId {1}", vuid, keyId);
            var partials = c1s.Select(c1 => (c1 * account.CVKi).ToByteArray())
                           .Select(bff => Convert.ToBase64String(sessionKey.Encrypt(bff)));

            return(Ok(string.Join(Environment.NewLine, partials)));
        }
        public async Task <string> GetAttachmentDownloadUrlAsync(Cipher cipher, CipherAttachment.MetaData attachmentData)
        {
            await InitAsync();

            return($"{_baseAttachmentUrl}/{cipher.Id}/{attachmentData.AttachmentId}");
        }
Exemple #41
0
        /**
        * writes to encrypted stream
        */
        public void WriteTo(AbstractGranadosSocket output, Cipher cipher)
        {
            byte[] image = BuildImage();
            //dumpBA(image);
            byte[] encrypted = new byte[image.Length - 4];
            cipher.Encrypt(image, 4, image.Length - 4, encrypted, 0); //length field must not be encrypted

            Array.Copy(encrypted, 0, image, 4, encrypted.Length);
            output.Write(image, 0, image.Length);
        }
Exemple #42
0
 public CipherWrapper(string transformation)
 {
     cipher = Cipher.GetInstance(transformation);
 }
Exemple #43
0
 public void SetCipher(Cipher c, bool check_mac)
 {
     _cipher = c;
     _checkMAC = check_mac;
 }
        static void makeResponseForChoice()
        {
            Console.Write("Zadejte vstup: ");
            string choice = Console.ReadLine();

            switch (choice)
            {
            case "1":
                Console.WriteLine(Environment.NewLine + "Nyní vytváříte nový profil");

                CipherSettings cipherSettings = new CipherSettings();
                Console.Write("Zadejte název profilu: ");
                cipherSettings.name = Console.ReadLine();
                var cipherSettingsResult = DatabaseFactory.DatabaseCipherSettings.SelectByName(cipherSettings.name).Result;
                if (cipherSettingsResult.Count() != 0)
                {
                    Console.WriteLine("účet s tímto jménem byl již vytvořen");
                    RunConsole();
                }

                Console.Write("Zadejte frázi pro generování šifry: ");
                cipherSettings.hashphrase = Console.ReadLine();

                CipherSettings.CreateNewSettings(cipherSettings);
                Console.WriteLine("Úspěšně vytvořen záznam" + Environment.NewLine);
                break;

            case "2":

                Cipher cipher = new Cipher();
                Console.Write("Zadejte název profilu pro dešifrování záznamu: ");
                cipherSettings       = new CipherSettings();
                cipherSettings.name  = Console.ReadLine();
                cipherSettingsResult = DatabaseFactory.DatabaseCipherSettings.SelectByName(cipherSettings.name).Result;
                if (cipherSettingsResult.Count() == 0)
                {
                    Console.WriteLine("Nebyl nalezen zadaný profil, prosím nejprve ho vytvořte");
                    RunConsole();
                }

                Console.Write("Zadejte cestu k souboru: ");
                cipher.path = Console.ReadLine();
                CheckFilePath(cipher.path);
                cipher.cryptedText = File.ReadAllText(cipher.path);
                cipher.text        = Cipher.TextEncryption(cipher.cryptedText, cipherSettingsResult[0].index);

                Console.WriteLine("Dešifrovaný text: {0}", cipher.text);


                break;

            case "3":
                Console.Write("Zadejte název profilu pro šifrování záznamu: ");
                cipherSettings       = new CipherSettings();
                cipherSettings.name  = Console.ReadLine();
                cipherSettingsResult = DatabaseFactory.DatabaseCipherSettings.SelectByName(cipherSettings.name).Result;
                if (cipherSettingsResult.Count() == 0)
                {
                    Console.WriteLine("Nebyl nalezen zadaný profil, prosím nejprve ho vytvořte");
                    RunConsole();
                }
                Console.Write("Zadejte šifrovaný text: ");
                cipher      = new Cipher();
                cipher.text = Console.ReadLine();
                Console.Write("Přejete si uložit text do souboru? Y/N : ");

                bool decision = DecisionMaker(Console.ReadLine());
                cipher.cryptedText = Cipher.TextEncryption(cipher.text, cipherSettingsResult[0].index, true);
                if (decision)
                {
                    Console.WriteLine("Soubor uložen zde:" + System.AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString("dd-MM-yyyy_H-mm-ss") + ".txt");
                    File.WriteAllText(@System.AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString("dd-MM-yyyy_H-mm-ss") + ".txt", cipher.cryptedText);
                }
                else
                {
                    Console.Write("Šifrovaný text: ");
                    Console.WriteLine(cipher.cryptedText);
                }
                break;

            case "4":
                cipherSettingsResult = DatabaseFactory.DatabaseCipherSettings.Select().Result;
                for (int i = 0; i < cipherSettingsResult.Count; i++)
                {
                    Console.WriteLine("Jméno: {0}, hashovací fráze: {1}, hash: {2}, index {3}",
                                      cipherSettingsResult[i].name,
                                      cipherSettingsResult[i].hashphrase,
                                      cipherSettingsResult[i].hash,
                                      cipherSettingsResult[i].index);
                }
                break;

            default:
                Console.WriteLine("Nezvolil jste správně");
                Console.WriteLine();
                Main(null);
                break;
            }
        }
Exemple #45
0
        static bool Is(Cipher algo, KernelMode mode)
        {
            // asking the kernel for availability turns out to be very costly
            long key = (((long)algo << 32) | (long)mode);

            if (availability.Contains(key))
            {
                return(true);
            }

            bool result = false;

            fixed(byte *k = &null_key[0])
            {
                Session session = new Session();

                switch (algo)
                {
                case Cipher.AES_CBC:
                case Cipher.AES_ECB:
                    session.cipher = algo;
                    session.keylen = 32;
                    session.key    = (IntPtr)k;
                    break;

                case Cipher.SHA1:
                    session.mac = algo;
                    break;

                // accept both SHA256 and SHA2_256 and use the correct one
                case Cipher.SHA256:
                case Cipher.SHA2_256:
                    if (mode == KernelMode.Ocf)
                    {
                        session.mac = Cipher.SHA2_256;
                    }
                    else
                    {
                        session.mac = Cipher.SHA256;
                    }
                    break;

                default:
                    return(false);
                }

                ulong ciocgsession = mode == KernelMode.CryptoDev ? CD_CIOCGSESSION : OCF_CIOCGSESSION;

                if (IntPtr.Size == 4)
                {
                    result = ioctl32(fildes, (int)ciocgsession, ref session) == 0;
                }
                else
                {
                    result = ioctl64(fildes, ciocgsession, ref session) == 0;
                }
            }

            if (result)
            {
                Mode = mode;
                availability.Add(key);
            }
            return(result);
        }
Exemple #46
0
        public async Task <IActionResult> Post([FromBody] IEnumerable <EventModel> model)
        {
            if (model == null || !model.Any())
            {
                return(new BadRequestResult());
            }
            var cipherEvents = new List <Tuple <Cipher, EventType, DateTime?> >();
            var ciphersCache = new Dictionary <Guid, Cipher>();

            foreach (var eventModel in model)
            {
                switch (eventModel.Type)
                {
                // User events
                case EventType.User_ClientExportedVault:
                    await _eventService.LogUserEventAsync(_currentContext.UserId.Value, eventModel.Type, eventModel.Date);

                    break;

                // Cipher events
                case EventType.Cipher_ClientAutofilled:
                case EventType.Cipher_ClientCopiedHiddenField:
                case EventType.Cipher_ClientCopiedPassword:
                case EventType.Cipher_ClientCopiedCardCode:
                case EventType.Cipher_ClientToggledCardCodeVisible:
                case EventType.Cipher_ClientToggledHiddenFieldVisible:
                case EventType.Cipher_ClientToggledPasswordVisible:
                case EventType.Cipher_ClientViewed:
                    if (!eventModel.CipherId.HasValue)
                    {
                        continue;
                    }
                    Cipher cipher = null;
                    if (ciphersCache.ContainsKey(eventModel.CipherId.Value))
                    {
                        cipher = ciphersCache[eventModel.CipherId.Value];
                    }
                    else
                    {
                        cipher = await _cipherRepository.GetByIdAsync(eventModel.CipherId.Value,
                                                                      _currentContext.UserId.Value);
                    }
                    if (cipher == null)
                    {
                        continue;
                    }
                    if (!ciphersCache.ContainsKey(eventModel.CipherId.Value))
                    {
                        ciphersCache.Add(eventModel.CipherId.Value, cipher);
                    }
                    cipherEvents.Add(new Tuple <Cipher, EventType, DateTime?>(cipher, eventModel.Type, eventModel.Date));
                    break;

                default:
                    continue;
                }
            }
            if (cipherEvents.Any())
            {
                foreach (var eventsBatch in cipherEvents.Batch(50))
                {
                    await _eventService.LogCipherEventsAsync(eventsBatch);
                }
            }
            return(new OkResult());
        }