Inheritance: ICipherParameters
Exemplo n.º 1
0
        public string Encrypt(string data)
        {
            SecureRandom random = new SecureRandom();

            // Generate 256-bits AES key
            byte[] aesKey = new byte[32];
            random.NextBytes(aesKey);

            // Generate Initialization Vector
            byte[] IV = new byte[12];
            random.NextBytes(IV);

            // Apply RSA/None/PKCS1Padding encryption to the AES key
            byte[] encyptedAESKey = rsaCipher.DoFinal(aesKey);

            // Apply AES/CCM/NoPadding encryption to the data
            byte[] cipherText = System.Text.Encoding.UTF8.GetBytes(data);

            var ccmParameters = new CcmParameters(new KeyParameter(aesKey), 64, IV, new byte[] { });
            aesCipher = new CcmBlockCipher(new AesFastEngine());
            aesCipher.Init(true, ccmParameters);

            var encrypted = new byte[aesCipher.GetOutputSize(cipherText.Length)];
            var res = aesCipher.ProcessBytes(cipherText, 0, cipherText.Length, encrypted, 0);
            aesCipher.DoFinal(encrypted, res);

            // Merge 'IV' and 'encrypted' to 'result'
            byte[] result = new byte[IV.Length + encrypted.Length];
            System.Buffer.BlockCopy(IV, 0, result, 0, IV.Length);
            System.Buffer.BlockCopy(encrypted, 0, result, IV.Length, encrypted.Length);

            // Return encrypted data
            return Prefix + Version + Separator + System.Convert.ToBase64String(encyptedAESKey) + Separator + System.Convert.ToBase64String(result);
        }
Exemplo n.º 2
0
Arquivo: Up1.cs Projeto: k3d3/ShareX
        public static Stream Encrypt(Stream stream, out string seed_encoded, out string ident_encoded, string fileName)
        {
            RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
            byte[] seed = new byte[16];
            rngCsp.GetBytes(seed);
            seed_encoded = UrlBase64Encode(seed);

            SHA512CryptoServiceProvider sha512csp = new SHA512CryptoServiceProvider();
            byte[] seed_result = sha512csp.ComputeHash(seed);
            byte[] key = new byte[32];
            Buffer.BlockCopy(seed_result, 0, key, 0, 32);

            byte[] iv = new byte[16];
            Buffer.BlockCopy(seed_result, 32, iv, 0, 16);

            byte[] ident = new byte[16];
            Buffer.BlockCopy(seed_result, 48, ident, 0, 16);
            ident_encoded = UrlBase64Encode(ident);
            var fi = new FileInfo(fileName);

            Dictionary<string, string> args = new Dictionary<string, string>();

            // text files aren't detected well by the "ClouDeveloper" mime type library, use ShareX's builtin list first.
            if (Helpers.IsTextFile(fileName))
            {
                args["mime"] = "text/plain";
            }
            else
            {
                var mimeOpts = ClouDeveloper.Mime.MediaTypeNames.GetMediaTypeNames(fi.Extension).ToList();
                args["mime"] = mimeOpts.Count > 0 ? mimeOpts[0] : "image/png";
            }
            args["name"] = fileName;

            byte[] d = Encoding.BigEndianUnicode.GetBytes(JsonConvert.SerializeObject(args));

            byte[] rawdata = d.Concat(new byte[] { 0, 0 }).Concat(stream.GetBytes()).ToArray();

            int l = FindIVLen(rawdata.Length);
            byte[] civ = new byte[l];
            Array.Copy(iv, civ, l);
            KeyParameter key_param = new KeyParameter(key);
            var ccmparams = new CcmParameters(key_param, MacSize, civ, new byte[0]);
            var ccmMode = new CcmBlockCipher(new AesFastEngine());
            ccmMode.Init(true, ccmparams);
            var encBytes = new byte[ccmMode.GetOutputSize(rawdata.Length)];
            var res = ccmMode.ProcessBytes(rawdata, 0, rawdata.Length, encBytes, 0);
            ccmMode.DoFinal(encBytes, res);

            return new MemoryStream(encBytes);
        }
Exemplo n.º 3
0
Arquivo: Up1.cs Projeto: aeax/ShareX
        private static MemoryStream Encrypt(Stream source, string fileName, out string seed_encoded, out string ident)
        {
            // Randomly generate a new seed for upload
            byte[] seed = new byte[16];

            using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider())
            {
                rngCsp.GetBytes(seed);
            }

            seed_encoded = UrlBase64Encode(seed);

            // Derive the parameters (key, IV, ident) from the seed
            byte[] key, iv;
            DeriveParams(seed, out key, out iv, out ident);

            // Create a new String->String map for JSON blob, and define filename and metadata
            Dictionary<string, string> metadataMap = new Dictionary<string, string>();
            metadataMap["mime"] = Helpers.IsTextFile(fileName) ? "text/plain" : Helpers.GetMimeType(fileName);
            metadataMap["name"] = fileName;

            // Encode the metadata with UTF-16 and a double-null-byte terminator, and append data
            // Unfortunately, the CCM cipher mode can't stream the encryption, and so we have to GetBytes() on the source.
            // We do limit the source to 50MB however
            byte[] data = Encoding.BigEndianUnicode.GetBytes(JsonConvert.SerializeObject(metadataMap)).Concat(new byte[] { 0, 0 }).Concat(source.GetBytes()).ToArray();

            // Calculate the length of the CCM IV and copy it over
            long ccmIVLen = FindIVLen(data.Length);
            byte[] ccmIV = new byte[ccmIVLen];
            Array.Copy(iv, ccmIV, ccmIVLen);

            // Set up the encryption parameters
            KeyParameter keyParam = new KeyParameter(key);
            CcmParameters ccmParams = new CcmParameters(keyParam, MacSize, ccmIV, new byte[0]);
            CcmBlockCipher ccmMode = new CcmBlockCipher(new AesFastEngine());
            ccmMode.Init(true, ccmParams);

            // Perform the encryption
            byte[] encBytes = new byte[ccmMode.GetOutputSize(data.Length)];
            int res = ccmMode.ProcessBytes(data, 0, data.Length, encBytes, 0);
            ccmMode.DoFinal(encBytes, res);

            return new MemoryStream(encBytes);
        }
Exemplo n.º 4
0
        public void Init(bool forEncryption, ICipherParameters parameters)
        {
            if (!(parameters is CcmParameters))
            {
                throw new ArgumentException("parameters need to be CCMParameters");
            }

            this.forEncryption = forEncryption;
            this.parameters = (CcmParameters)parameters;
        }
Exemplo n.º 5
0
 /// <summary>
 /// Encrypt the message using the passed key and pre-calculated nonce.
 /// </summary>
 /// <param name="messageBytes"></param>
 /// <param name="encryptionKeyHex"></param>
 /// <param name="nonceBytes"></param>
 /// <returns></returns>
 private static byte[] EncryptMessage(byte[] messageBytes, string encryptionKeyHex, byte[] nonceBytes)
 {
     if (string.IsNullOrEmpty(encryptionKeyHex))
         return messageBytes;
     var key = StringToByteArray(encryptionKeyHex);
     var cipher = new CcmBlockCipher(new AesFastEngine());
     var parameters = new CcmParameters(new KeyParameter(key), 64, nonceBytes, new byte[] {});
     //var parameters = new CcmParameters(new KeyParameter(key), 64, nonceBytes, System.Text.Encoding.UTF8.GetBytes("testing much data"));
     cipher.Init(true, parameters);
     var encryptedBytes = new byte[cipher.GetOutputSize(messageBytes.Length)];
     var res = cipher.ProcessBytes(messageBytes, 0, messageBytes.Length, encryptedBytes, 0);
     cipher.DoFinal(encryptedBytes, res);
     return encryptedBytes;
 }
Exemplo n.º 6
0
        private static byte[] DecryptMessage(byte[] encryptedBytes, string encryptionKeyHex)
        {
            if (string.IsNullOrEmpty(encryptionKeyHex))
                return encryptedBytes;

            var headerBytes = encryptedBytes.Take(1).ToArray(); // 0xFF
            var nonceBytes = encryptedBytes.Skip(1).Take(7).ToArray();
            encryptedBytes = encryptedBytes.Skip(8).ToArray();
            var key = StringToByteArray(encryptionKeyHex);
            var cipher = new CcmBlockCipher(new AesFastEngine());
            var parameters = new CcmParameters(new KeyParameter(key), 64, nonceBytes, new byte[] { });
            cipher.Init(false, parameters);
            var plainBytes = new byte[cipher.GetOutputSize(encryptedBytes.Length)];
            var res = cipher.ProcessBytes(encryptedBytes, 0, encryptedBytes.Length, plainBytes, 0);
            cipher.DoFinal(plainBytes, res);

            return plainBytes;
        }
Exemplo n.º 7
0
        public static string Decrypt(string password, string data)
        {
            SJCLBlob ctdata = JsonConvert.DeserializeObject<SJCLBlob>(data);
            if (ctdata.Cipher != "aes" || ctdata.Mode != "ccm")
                throw new InvalidOperationException("Unsupported cipher or mode.");
            byte[] cipherText = DecodeBase64(ctdata.CipherText);
            var derivedMacParameters = DeriveKey(password, ctdata);

            var l = FindIVLen(cipherText.Length);
            byte[] iv = new byte[l];
            Array.Copy((Array) DecodeBase64(ctdata.IV), (Array) iv, (int) l);

            var ccmparams = new CcmParameters(derivedMacParameters, ctdata.TagSize, iv, DecodeBase64(ctdata.AuthData));
            var ccmMode = new CcmBlockCipher(new AesFastEngine());
            ccmMode.Init(false, ccmparams);
            var plainBytes = new byte[ccmMode.GetOutputSize(cipherText.Length)];
            var res = ccmMode.ProcessBytes(cipherText, 0, cipherText.Length, plainBytes, 0);
            ccmMode.DoFinal(plainBytes, res);
            return Encoding.UTF8.GetString(plainBytes);
        }
Exemplo n.º 8
0
        public static string Encrypt(string password, string data)
        {
            RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
            byte[] salt = new byte[8];
            rngCsp.GetBytes(salt);
            byte[] iv = new byte[16];
            rngCsp.GetBytes(iv);

            SJCLBlob ctdata = new SJCLBlob()
                {
                    Mode = "ccm",
                    Cipher = "aes",
                    AuthData = "",
                    Iterations = 2000,
                    KeySize = 256,
                    TagSize = 64,
                    Salt = Convert.ToBase64String(salt),
                    IV = Convert.ToBase64String(iv),
                    V = 1
                };
            var key = DeriveKey(password, ctdata);
            byte[] rawdata = Encoding.UTF8.GetBytes(data);
            var l = FindIVLen(rawdata.Length);
            byte[] civ = new byte[l];
            Array.Copy((Array) iv, (Array) civ, (int) l);

            var ccmparams = new CcmParameters(key, ctdata.TagSize, civ, DecodeBase64(ctdata.AuthData));
            var ccmMode = new CcmBlockCipher(new AesFastEngine());
            ccmMode.Init(true, ccmparams);
            var encBytes = new byte[ccmMode.GetOutputSize(rawdata.Length)];
            var res = ccmMode.ProcessBytes(rawdata, 0, rawdata.Length, encBytes, 0);
            ccmMode.DoFinal(encBytes, res);
            ctdata.CipherText = Convert.ToBase64String(encBytes);

            return JsonConvert.SerializeObject(ctdata);
        }