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Jpc3MiOiJTYWJhIElkZWEgR1NJRyJ9.vvYKPY9tyBnhGGnNtY-XLy_Hz5cyJx5Ma2APVv0g5dk
#EXTINF:12.000,
s-4-v1-a1.ts?wmsAuthSign=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbiI6IjdjY2I5ZTAxZGI1YzVkM2IzMWUzMzc1NzQ3MjZjNjYwIiwiZXhwIjoxNTEzMTU4ODM5LCJpc3MiOiJTYWJhIElkZWEgR1NJRyJ9.vvYKPY9tyBnhGGnNtY-XLy_Hz5cyJx5Ma2APVv0g5dk
we have both enc.key file and the server response to 'enc.key' that is DVQpuWrxZLd2nCTTxAysIg==
we are using these C# functions for decryption but we don't know how to find salt or block size ? or basically we are doing it in correct way ?
public static void DecryptFile(string inputFile, string output,string password)
{
byte[] bytesToBeDecrypted = File.ReadAllBytes(inputFile);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
byte[] bytesDecrypted = AES_Decrypt(bytesToBeDecrypted, passwordBytes);
File.Delete(inputFile);
File.WriteAllBytes(output, bytesDecrypted);
}
public static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
{
byte[] decryptedBytes = null;
// Set your salt here, change it to meet your flavor:
// The salt bytes must be at least 8 bytes.
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 128;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
AES.Padding = PaddingMode.PKCS7;
using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
cs.Close();
}
decryptedBytes = ms.ToArray();
}
}
return decryptedBytes;
}

There was already a similar quesion here (unable to find it back)
how to find salt or block size
Look at your EXT-X-KEY header. It states AES-128, so you will have to use AES-128 (it's the key size, block size is always 128 bit).
According to the RFC by default CBC mode with Pkcs7 padding is used.
The section 4.3.2.4. EXT-X-KEY further states: the Initialization Vector (IV) attribute value or the Media Sequence Number as the IV
So the IV should be present in the EXT-X-KEY header. If not, the sequence number is used (which is terrible idea for CBC, but this is how it is).
or basically we are doing it in correct way
Basically it looks ok (except the salt and key). I am not sure what is the encryption key. The encoded response from the server has 16 bites (128 bits) so I'd assume that can be the key (that you will have to find out yourself)

Related

Python decryption not matching .NET encryption

Python Encryption:
salt = 16 * b'\0'
keyIV = PBKDF2(Config.SECRET, salt).read(48)
key = keyIV[:32]
iv = keyIV[-16:]
aes = AES.new(key, AES.MODE_CBC, iv)
# padding
length = 16 - (len(textToEncrypt) % 16)
print(len(textToEncrypt))
textToEncrypt += length * b'\0'
encrypted = aes.encrypt(textToEncrypt)
encoded = base64.b64encode(encrypted)
return encoded
And here is my C# decryption:
textToDecrypt = textToDecrypt.Replace(" ", "+");
byte[] bytesToDecrypt = Convert.FromBase64String(textToDecrypt);
string decryptedText;
using (Aes aes = Aes.Create())
{
byte[] salt = new byte[16];
Rfc2898DeriveBytes crypto = new Rfc2898DeriveBytes(Config.SECRET, salt);
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.CBC;
aes.Key = crypto.GetBytes(32);
aes.IV = crypto.GetBytes(16);
using (MemoryStream mStream = new MemoryStream())
{
using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cStream.Write(bytesToDecrypt, 0, bytesToDecrypt.Length);
}
decryptedText = Encoding.Unicode.GetString(mStream.ToArray());
}
}
return decryptedText;
EDIT
Following #kelalaka answer, I'm now able to encrypt from C# and decrypt that string in python successfully, but not vice versa. That is, if I encrypt a string in python, and try to decrypt that encryption in C# I get an exception: "Bad PKCS7 padding. Invalid length 0". My python encryption is much shorter than what I get in C# using the same cipherText, iv, and key.

Trying to decrypt a string using AES Managed

I am trying to write code to decrypt a string.
I was given an equivalent in python and I am trying to create the same in . NET
Python:
//Initialization vector is just a string of 16 null bytes
iv = '\x00' * 16
//Create new AES object using the key and init vector
aes = AES.new(key, AES.MODE_CBC, iv)
//Decrypt password and remove padding
result = aes.decrypt(myString).rstrip('\x0b\x08\x07')
return result
Here is my attempt:
byte[] iv = new byte[16];
byte[] rawPlaintext = Convert.FromBase64String("MyBase64String");
byte[] key = // Read from common source
using (Aes aes = new AesManaged())
{
aes.Padding = PaddingMode.None;
aes.KeySize = 128; // in bits
aes.Key = new byte[128 / 8]; // 16 bytes for 128 bit encryption
aes.IV = new byte[128 / 8]; // AES needs a 16-byte IV
// Should set Key and IV here. Good approach: derive them from
// a password via Cryptography.Rfc2898DeriveBytes
byte[] cipherText = key;
byte[] plainText = iv;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(rawPlaintext, 0, rawPlaintext.Length);
}
cipherText = ms.ToArray();
}
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherText, 0, cipherText.Length);
}
plainText = ms.ToArray();
}
string s = System.Text.Encoding.Unicode.GetString(plainText);
Console.WriteLine(s);
}
It doesn't appear to be working for the result is a string of symbols.
Possible issues:
- I see a mode of CBC getting set. I'm not sure where that equivalent setting would be. I've tried to play with the PaddingMode.
- Could my iv byte[] be causing the issue? Is the default null or 0?
EDIT:
- From what I am reading AesManaged uses AES in CBC mode so that should be a non-issue.
Try replacing this:
string s = System.Text.Encoding.Unicode.GetString(plainText);
to:
string s = System.Text.Encoding.UTF8.GetString(plainText);

RijndaelManaged - encrypt in C# and decrypt in Java

I have c sharp code snippet for encryption which uses .Key file for key and my requirement is to decrypt the encrypted text using same key in android, having problem
public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes) {
byte[] encryptedBytes = null;
// Set your salt here, change it to meet your flavor:
// The salt bytes must be at least 8 bytes.
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
If you want to decrypt some data with AES you can use this method:
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
for complete code look at : android encryption/decryption with AES

Creating/Decrypt passwords with Salt/IV

I've been ask to do a task in a project that involves encryption on a windows 8.
The scenario is something like this:
I get a byte[] from a server, the first 16 bytes are the IV, the next 128 are the Salt and the remaining ones are the File itself.
The user then provides a password and with that and the salt i should create a PKCS5 Key with 40 iterations and the key should have 32bytes length.
Right now i've splitted the byte[] in th 3 i require, but i dont know how the rest is done in windows C#.
I've done some work with encryption/decryption, but let me give you the resource I used for AES 256 bit encryption. Hopefully this will give you an idea of how to switch it over to PKCS5, but everything else I'm pretty sure is the same. It's a little lengthy, but let me know if this applies to your situation. I'm curious how much different it would be for PKCS5 instead of AES256.
Edit: Because the code they posted wasn't clear on the iterations, the iterations is controlled by the line var key = Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); using 1000 iterations.
http://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt
Core Encryption Code
using System.Security.Cryptography;
using System.IO;
Encryption
public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
// Set your salt here, change it to meet your flavor:
// The salt bytes must be at least 8 bytes.
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
Decryption
public byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
{
byte[] decryptedBytes = null;
// Set your salt here, change it to meet your flavor:
// The salt bytes must be at least 8 bytes.
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
cs.Close();
}
decryptedBytes = ms.ToArray();
}
}
return decryptedBytes;
}
Getting Randomized Encryption Result with Salt
If we encrypt the same context (i.e. string of "Hello World") for 10 times, the encrypted results will be the same. What if we want the results different from each time it is encrypted?
What I do is appending a random salt bytes in front of the original bytes before encryption, and remove it after decryption.
Example of Appending Randomized Salt Before Encrypting a String
public string Encrypt(string text, string pwd)
{
byte[] originalBytes = Encoding.UTF8.GetBytes(text);
byte[] encryptedBytes = null;
byte[] passwordBytes = Encoding.UTF8.GetBytes(pwd);
// Hash the password with SHA256
passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
// Generating salt bytes
byte[] saltBytes = GetRandomBytes();
// Appending salt bytes to original bytes
byte[] bytesToBeEncrypted = new byte[saltBytes.Length + originalBytes.Length];
for (int i = 0; i < saltBytes.Length; i++)
{
bytesToBeEncrypted[i] = saltBytes[i];
}
for (int i = 0; i < originalBytes.Length; i++)
{
bytesToBeEncrypted[i + saltBytes.Length] = originalBytes[i];
}
encryptedBytes = AES_Encrypt(bytesToBeEncrypted, passwordBytes);
return Convert.ToBase64String(encryptedBytes);
}
Example of Removing the Salt after Decryption
public string Decrypt(string decryptedText, string pwd)
{
byte[] bytesToBeDecrypted = Convert.FromBase64String(decryptedText);
byte[] passwordBytes = Encoding.UTF8.GetBytes(pwd);
// Hash the password with SHA256
passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
byte[] decryptedBytes = AES_Decrypt(bytesToBeDecrypted, passwordBytes);
// Getting the size of salt
int _saltSize = 4;
// Removing salt bytes, retrieving original bytes
byte[] originalBytes = new byte[decryptedBytes.Length - _saltSize];
for (int i = _saltSize; i < decryptedBytes.Length; i++)
{
originalBytes[i - _saltSize] = decryptedBytes[i];
}
return Encoding.UTF8.GetString(originalBytes);
}
Code for getting random bytes
public byte[] GetRandomBytes()
{
int _saltSize = 4;
byte[] ba = new byte[_saltSize];
RNGCryptoServiceProvider.Create().GetBytes(ba);
return ba;
}
Step 1: Split the incoming data into IV, salt and cyphertext. You say you have done this.
Step 2: Pass the supplied password and the salt from step 1 as inputs to the PKCS5 key generation method, using 40 iterations. There should be a PKCS5 class in your crypto library. The output from this step will be a key.
Step 3: Use the key from step 2 and the IV from step 1 to decrypt the cyphertext from step 1. Use the specified decryption algorithm, probably AES, in the specified mode. Since an IV is supplied then it is likely that CBC mode is intended, so you will probably need to use the AES-CBC mode from your cypher library. Check the problem specification to confirm both algorithm and cypher mode -- I am only guessing here.
If you have a problem with any of these steps, ask here again, showing your code and explaining the errors you are getting.

Encrypt String AES Windows Phone 8.1

I'm making an app which will need to encrypt a string.
I'm completely new to AES encryption.
I have to code that runs on the server to encrypt.
public static string Encrypt(string text, byte[] key, byte[] iv, int keysize = 128, int blocksize = 128, CipherMode cipher = CipherMode.CBC, PaddingMode padding = PaddingMode.PKCS7)
{
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.BlockSize = blocksize;
aes.KeySize = keysize;
aes.Mode = cipher;
aes.Padding = padding;
byte[] src = Encoding.UTF8.GetBytes(text);
using (ICryptoTransform encrypt = aes.CreateEncryptor(key, iv))
{
byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
encrypt.Dispose();
return Convert.ToBase64String(dest);
}
}
I already have this, with a library Bouncy Castle, but I can't seem to find a simple example.
byte[] key = Encoding.UTF8.GetBytes("[SECRETKEY]");
byte[] iv = Encoding.UTF8.GetBytes("[IV]");
var cipher = CipherUtilities.GetCipher("AES/CBC/PKCS7Padding");
cipher.Init(true, new KeyParameter(key));
If it can help I also have the code which runs an Android client.
Let me know then I can post it.
You can use the PCLCrypto library, there's a nuget package available (Install-Package PclCrypto)
From https://github.com/AArnott/PCLCrypto/wiki/Crypto-Recipes:
Perform AES encryption/decryption
byte[] keyMaterial;
byte[] data;
var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
var key = provider.CreateSymmetricKey(keyMaterial);
byte[] iv = null; // this is optional, but must be the same for both encrypting and decrypting
byte[] cipherText = WinRTCrypto.CryptographicEngine.Encrypt(key, data, iv);
byte[] plainText = WinRTCrypto.CryptographicEngine.Decrypt(key, cipherText, iv);
The cipherText variable is the encrypted data, plainText is the encrypted variable decrypted again

Categories