I am developing an android application in which i need to implement some encryption.
At the same time i have to keep compatibility with other versions of application (e.g. for the WP platform), which are already in production.
This is C# code:
static public byte[] Encrypt(String passphrase, byte[] data)
{
//encrypted data
byte[] buffer = null;
//crypto handles
IntPtr hProvider = IntPtr.Zero;
IntPtr hKey = IntPtr.Zero;
try
{
if (!WinApi.CryptAcquireContext(ref hProv, null, WinApi.MS_DEF_PROV,
WinApi.PROV_RSA_FULL, WinApi.CRYPT_VERIFYCONTEXT))
Failed("CryptAcquireContext");
//128 bit hash object
if (!WinApi.CryptCreateHash(hProv,
WinApi.CALG_MD5, IntPtr.Zero, 0, ref hHash))
Failed("CryptCreateHash");
// add passphrase to hash
byte[] keyData = ASCIIEncoding.ASCII.GetBytes(passphrase);
if (!WinApi.CryptHashData(hHash, keyData, (uint)keyData.Length, 0))
Failed("CryptHashData");
// create 40 bit crypto key from passphrase hash
if (!WinApi.CryptDeriveKey(hProv, WinApi.CALG_RC2,
hHash, WinApi.CRYPT_EXPORTABLE, ref hKey))
Failed("CryptDeriveKey");
// determine how large of a buffer is required
// to hold the encrypted data
uint dataLength = (uint)data.Length;
uint bufLength = (uint)data.Length;
if (!WinApi.CryptEncrypt(hKey, IntPtr.Zero, true,
0, null, ref dataLength, bufLength))
Failed("CryptEncrypt");
// allocate and fill buffer with encrypted data
buffer = new byte[dataLength];
Buffer.BlockCopy(data, 0, buffer, 0, data.Length);
dataLength = (uint)data.Length;
bufLength = (uint)buffer.Length;
if (!WinApi.CryptEncrypt(hKey, IntPtr.Zero, true,
0, buffer, ref dataLength, bufLength))
Failed("CryptEncrypt");
}
.......
}
I have tried to implement it in Java. AFAIK, there is no default RC2 crypto provider in android, so i used Spongy Castle library (bouncycastle fork for android).
This is my Java code:
public static byte[] encryptLB(byte[] key, byte[] iv, byte[] unencrypted)
throws NoSuchAlgorithmException, ... {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(key);
byte[] hash = digest.digest(); //build the hash (128 bit)
Cipher cipher = Cipher.getInstance("RC2/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(hash, "RC2"));
byte[] unByte = unencrypted;
byte[] encrypted = cipher.doFinal(unencrypted);
return encrypted;
}
And the results of these functions are different.
What i am doing wrong?
How do i do it right?
Any examples and suggestions are welcome.
With best regards.
UPD The main goal is to get identical byte arrays from both functions. I can't modify c# code. First, i want to clarify am i right with c#-code:
it creates MD5 hash from the passphrase's bytes array
it generates crypto key using proprietary WinApi.CryptDeriveKey function
this key is used to encrypt data using RC2 algorithm
Second, i want to know whether there is an analogue of WinApi.CryptDeriveKey function - as i see this is the main problem.
Sorry, my question is too general, because i am not sure that the problem above (CryptDeriveKey) is the only.
Unfortunately I don't have access to a Windows machine to test this on right now but here is what I think should be interoperable.
public static byte[] encrypt(String passphrase, byte[] data) throws Exception {
// Hash the ASCII-encoded passphrase with md5
byte[] keyData = passphrase.getBytes(Charset.forName("US-ASCII"));
MessageDigest md = MessageDigest.getInstance("MD5");
byte [] md5HashOfKey = md.digest(keyData);
// Need to use bouncycastle (spongycastle on Android) to get RC2
Security.addProvider(new BouncyCastleProvider());
Cipher rc2 = Cipher.getInstance("RC2/CBC/PKCS5PADDING");
// Create an RC2 40-bit key from the 1st 5 bytes of the hash.
SecretKeySpec rc2KeySpec = new SecretKeySpec(md5HashOfKey, 0, 5, "RC2");
rc2.init(Cipher.ENCRYPT_MODE, rc2KeySpec);
byte [] cipher = rc2.doFinal(data);
return cipher;
}
Related
Background: I have two devices which communicate via IP/port connection establishing live voice encrypting communication thanks to Diffie-Hellman key-exchange and encrypting it thanks to AES algorithm. Now some of the code is written and some just taken to use as an example of the prototype implementation.
Problem: Now even when understanding how my classes work just like the title states: I can not figure out how to take the key from DH class and declare in AES class that this is the key it must use to encrypt.
P.s. Advice on code optimization, better practices and general tips are most welcome, please.
Thank you for your time.
public class DH extends Thread {
int bitLength=512;
int certainty=20;//
private static final SecureRandom rnd = new SecureRandom();
public DH() throws Exception{
Random randomGenerator = new Random();
BigInteger generatorValue,primeValue,publicA,publicB,secretA,secretB,sharedKeyA,sharedKeyB;
primeValue = findPrime();// BigInteger.valueOf((long)g);
System.out.println("the prime is "+primeValue);
generatorValue = findPrimeRoot(primeValue);//BigInteger.valueOf((long)p);
System.out.println("the generator of the prime is "+generatorValue);
// on machine 1
secretA = new BigInteger(bitLength-2,randomGenerator);
// on machine 2
secretB = new BigInteger(bitLength-2,randomGenerator);
// to be published:
publicA=generatorValue.modPow(secretA, primeValue);
publicB=generatorValue.modPow(secretB, primeValue);
sharedKeyA = publicB.modPow(secretA,primeValue);// should always be same as:
sharedKeyB = publicA.modPow(secretB,primeValue);
String getAValue=sharedKeyA.toString();
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(getAValue.getBytes());
byte byteData[] = md.digest();
StringBuffer sb = new StringBuffer();
for(int i=0;i<byteData.length;i++)
{
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));// ??
}
String getHexValue = sb.toString();
System.out.println("hex format in SHA-256 is "+getHexValue);
byte [] initkey = getAValue.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-256");
initkey = sha.digest(initkey);
initkey = Arrays.copyOf(initkey, 16);
SecretKeySpec secretKeySpec = new SecretKeySpec(initkey,"AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
}
As you can see i have coded AES key and IV statically but want for the generated AES key in DH to be assigned in this class
public class AES {
static String IV = "AAAAAAAAAAAAAAAA";
static String initkey = "13B_0(wcXNGkHAR[";
public static byte[] encrypt(byte[] plainData, int offset, int length) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");//CBC
SecretKeySpec key = new SecretKeySpec(initkey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
return cipher.doFinal(plainData, offset, length);
}
public static byte[] decrypt(byte[] cipherSound, int offset, int length) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");//CBC
SecretKeySpec key = new SecretKeySpec(initkey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
return cipher.doFinal(cipherSound, offset, length);
}
}
figure out how to take the key from DH class and declare in AES class that this is the key it must use to encrypt
Please check this tutorial
Then you can use the returned secret:
byte[] masterKey = aKeyAgree.generateSecret();
// maybe hash the master key too
SecretKeySpec key = new SecretKeySpec(masterKey, 0, 16, "AES");
However, if you have two way communication, you either need random IV or different keys for each direction (derived from the master)
Additional hint :
I have two devices which communicate via IP/port connection establishing live voice encrypting communication
Maybe your devices are powerful enough to establish proper TLS, what would solve many things for you
I am trying to decrypt a String with a known key in Java using standard Cipher API.
The encrypted String comes from a Web Service using the standard CommonCrypto Library which responds with some statistics as encrypted strings at regular intervals.
The specs are AES/CBC/PKCS7Padding with KeySize = 32 Bytes and BlockSize = 16 Bytes, and Encoding UTF-8 (raw) & Base64. I intend to write a Java client that can request these statistics, decrypt them and store them for later analyses.
Question 1. Does the CommonCrypto automatically pad keys with extra chars if the key is short? For instance less than 16 Bytes or 32 Bytes.
Question 2. What encoding measures should I take to ensure an identical encryption/decryption on both ends?
Example Strings and Key
String message = "mQp9sp8ri1E0V1Xfso1d5g==Mrf3wtaqUjASlZmUO+BI8MrWsrZSC0MxxMocswfYnqSn/VKB9luv6E8887eCxpLNNAOMB0YXv6OS7rFDFdlvC53pCHo3cVZiLJFqgWN/eNiC9p4RMxyFCcOzWrwKzT5P8sy55DwE25DNJkvMthSaxK5zcP1OdLgBiZFOSxYRsX4rBk7VP7p5xr2uTGjRL+jmGgB9u3TmeCNCr8NxGLNt6g==";
String userKey = "123456789";
private static String decrypt (String message, String userKey) throws UnsupportedEncodingException,
NoSuchPaddingException,
NoSuchAlgorithmException,
InvalidKeyException,
ShortBufferException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, NoSuchProviderException {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
if (message.length() >= 48) {
ivFromEncryptedString = message.substring(0, Math.min(message.length(), 24));
messageFromEncryptedString = message.substring(24, message.length());
System.out.println(ivFromEncryptedString);
System.out.println(messageFromEncryptedString);
byte[] data = decodeBase64(messageFromEncryptedString);
byte[] ivData = decodeBase64(ivFromEncryptedString);
paddedKey = padShortKeys(userKey);
byte[] keyBytes = paddedKey.getBytes(CHARSET);
MessageDigest sha = MessageDigest.getInstance("SHA-256"); //key
keyBytes = sha.digest(keyBytes);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivData);
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);
byte [] encrypted = new byte[cipher.getOutputSize(data.length)];
int ctLength = cipher.update(data, 0, data.length, encrypted, 0);
ctLength += cipher.doFinal(encrypted, ctLength);
} catch (Exception e) {
System.out.println(e);
} finally {
return encrypted;
}
}
return null;
}
private static String encodeBase64(byte [] in){
return Base64.getEncoder().encodeToString(in);
}
private static byte[] decodeBase64(String str) throws UnsupportedEncodingException {
return DatatypeConverter.parseBase64Binary(str);
}
Also with the current code status I am getting placehoder characters instead of the desired result.
Thanks in advance folks. :)
CommonCrypto is unclear, which implementation are you using? Apple, Apache, Java Class Cipher or another, please supply a link to it.
Never assume an encryption will pad the key or IV, they should always be provided in the exact length, there is no standard for such padding. If they need padding (they shouldn't) do it yourself.
Typically if encrypted data needs to be expressed as a character string Base64 encoding is used.
As James states, for one-shot encryption just use doFinal(ByteBuffer input, ByteBuffer output) which
encrypts or decrypts data in a single-part operation.
Note: A 9 digit key only has about 33-bits of security which is not close to sufficient. Simple using a hash function is insufficient for deriving an encryption key from a password, instead PBKDF2 or Argon2 should be used.
I'm try to be compatible Encrypt/Decrypt both C# and Java.
As I know the default mode is 'ecb/pkcs5' in Java, and 'cbc/pkcs7' in C#.
So I match these things.
1st question is that PKCS7 and PKCS5 are compatible each other??,
there is no PKCS7 in Java so I use PKCS5. but I can get same encrypted data [even the padding-way is different ,pkcs7/pkcs5,] Is it possible? or these are compatible?
2nd question is that Why I get same result even though the mode, way are all different?
I compare 'DES-ECB / DES-CBC / TripleDES-ECB' these things. and C# is working well, results are all different.
Input > HELLO Output > (ECB)/dZf3gUY150= (CBC) V17s5QLzynM= (Triple)sWGS0GMe1jE
but I get same reulst in Java ..
Input > HELLO Output > (ECB)/dZf3gUY150= (CBC)/dZf3gUY150= (Triple)/dZf3gUY150=
When debugging the flow is right.
Here is my code.
C#
public static string Encrypt_DES(string originalString, byte[] key, string mode)
{
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
if (mode.Equals("ECB"))
cryptoProvider.Mode = CipherMode.ECB;
else if (mode.Equals("CBC"))
{
cryptoProvider.Mode = CipherMode.CBC;
cryptoProvider.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
}
cryptoProvider.Padding = PaddingMode.PKCS7;
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(key, key), CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cryptoStream);
writer.Write(originalString);
writer.Flush();
cryptoStream.FlushFinalBlock();
writer.Flush();
return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
}
public static string Encrypt_TripleDES(string source, string key)
{
TripleDESCryptoServiceProvider desCryptoProvider = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider hashMD5Provider = new MD5CryptoServiceProvider();
byte[] byteHash;
byte[] byteBuff;
byteHash = hashMD5Provider.ComputeHash(Encoding.UTF8.GetBytes(key));
desCryptoProvider.Key = byteHash;
desCryptoProvider.Mode = CipherMode.ECB; //CBC, CFB
desCryptoProvider.Padding = PaddingMode.PKCS7;
byteBuff = Encoding.UTF8.GetBytes(source);
string encoded = Convert.ToBase64String(desCryptoProvider.CreateEncryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
return encoded;
}
Java(Android)
public String Encrypt(String str, String desKey, String mode) {
try {
KeySpec keySpec = null;
SecretKey key = null;
Cipher ecipher = null;
if (desKey.length() == 8) {
keySpec = new DESKeySpec(desKey.getBytes("UTF8"));
key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);
if(mode.equals(ECB)){
ecipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
ecipher.init(Cipher.ENCRYPT_MODE, key);
}else if (mode.equals(CBC)){
ecipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
ecipher.init(Cipher.ENCRYPT_MODE, key,ivSpec);
}
} else if (desKey.length() == 24) {
keySpec = new DESedeKeySpec(desKey.getBytes("UTF8"));
key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);
ecipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
ecipher.init(Cipher.ENCRYPT_MODE, key);
}
byte[] data = str.getBytes("UTF-8");
byte[] crypt = ecipher.doFinal(data);
return Base64.encodeToString(crypt, 0);
} catch (Exception ex) {
Log.d("ZVM", ex.getMessage());
}
return null;
}
As I understand 'IV' is for CBC, When making password, it is mixed with IV(not the key but like key). Is it right?
Thanks.
PKCS7 and PKCS5 are compatible each other
PKCS#5 and PKCS#7 paddings are compatible (equal) for DES. For AES, Java actually uses PKCS#7 padding even though you would write AES/xyz/PKCS5Padding.
Why I get same result even though the mode, way are all different?
First, let's see how Java behaves. The ciphertexts for DES-ECB, DES-CBC and DESede-ECB are all equal. This is correct if
the key is the same (DES supports only 8 byte keys, but Triple DES supports 8, 16 and 24 byte keys where non-24 byte keys are expanded to 24 byte keys),
the plaintext is the same,
the plaintext is less than 8 bytes long (block size of DES/Triple DES) and
the IV is an all 0x00 bytes IV.
Those are all true in the Java code. If you have trouble grasping that, combine the encryption routines for the ECB and CBC modes of operation.
The result of Triple DES might be a bit confusing. I assume that you've taken your 8 byte key for DES and replicated it either twice or thrice for use in Triple DES. This is an issue, because Triple DES encryption consists of three steps of normal DES: EDE means Encryption + Decryption + Encryption. If all the three subkeys are the same, the one of the Encryption steps cancels out with the Decryption step and the whole thing is equivalent to a single DES encryption.
Let's see why C# behaves differently:
The ciphertext from DES-CBC is different from DES-ECB, because the IV is not an all 0x00 bytes IV. cryptoProvider.CreateEncryptor(key, key) creates an Encryptor with the IV set to key (the second argument). That's not what you want. Just use cryptoProvider.CreateEncryptor() instead.
The ciphertext from DESede-ECB is different from DES-ECB, because you're running the key through a hash function. The key is therefore different.
Don't use DES nowadays. It only provides 56 bit of security. AES would be a much better, because it's more secure with the lowest key size of 128 bit. There is also a practical limit on the maximum ciphertext size with DES. See Security comparison of 3DES and AES.
The encrypted text is done in JAVA (which we have no JAVA background at all)
The decryption will be in C#, and here is the code
public static string DecryptString(string Message, string Passphrase)
{
byte[] Results;
UTF8Encoding UTF8 = new UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
// byte[] TDESKey = UTF8.GetBytes(Passphrase);
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
// TDESAlgorithm.Mode = CipherMode.CTS;
TDESAlgorithm.Padding = PaddingMode.Zeros;
byte[] DataToDecrypt = Convert.FromBase64String(Message);
try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return Encoding.UTF8.GetString(Results);
}
Encrypted Java code is
public String encryptData(String privateKey, String rawData)
{
Cipher cipher = null;
try
{
cipher = Cipher.getInstance(DESEDE_ENCRYPTION_SCHEME);
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(privateKey));
byte[] plainText = rawData.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
return new String(Base64.encodeBase64(encryptedText));
}
}
However, when tried to decrypt, got the error message: BAD DATA
Where am I missing here?
You are not using MD5 in Java, so you should not be using it in your .NET for computing the hash.
Your key should have been generated using a specific encoding and same you should use in .NET.
Please note, there is some fundamental difference in java KeySpec and the Key being used for TripleDESCryptoServiceProvider. As mentioned by Microsfot https://msdn.microsoft.com/en-us/library/system.security.cryptography.tripledescryptoserviceprovider.aspx
Triple DES only supports "key lengths from 128 bits to 192 bits in increments of 64 bits"
So you need to convert your key appropriately before assigning. To do this you can use the Array.Resize method as following.
byte[] TDESKey = Encoding.UTF8.GetBytes(Passphrase);
System.Array.Resize(ref TDESKey , 192 / 8);
Hope this will help.
I am in the process of implementing a Java library in Ruby. I have come across the following road block. Is it possible to implement the following code in ruby? Are there any ruby equivalents for byte[], IvParameterSpec, SecretKeySpec ?
private String decrypt(String token)
{
//parse token into its IV and token components
byte[] ivAndToken = Base64.decodeBase64(token);
byte[] iv = new byte[ivLength];
System.arraycopy(ivAndToken, 0, iv, 0, ivLength);
int length = ivAndToken.length - ivLength;
byte[] tokenBytes = new byte[length];
System.arraycopy(ivAndToken, ivLength, tokenBytes, 0, length);
//prepare initialization vector specification
IvParameterSpec spec = new IvParameterSpec(iv);
//create cipher instance based on transformer params
Cipher cipher = Cipher.getInstance(algorithm + mode + padding, CRYPTO_PROVIDER);
//convert key bytes into valid key format
Key key = new SecretKeySpec(Base64.decodeBase64(symkey), algorithm);
//initialize cipher for decryption
cipher.init(Cipher.DECRYPT_MODE, key, spec);
//decrypt the payload
String plaintext = new String(cipher.doFinal(tokenBytes));
return plaintext;
}
You'll probably have to implement both IvParameterSpec and SecretKeySpec on Ruby if you want the algorithm to behave exactly like it does in Java. byte[] is of course just a byte array. You'll probably want to at the docs for them (links above) and also hopefully you understand block cipher operation modes work.
If you don't, SecretKey refers to the symmetric key (eg: the passphrase), and IV is the initialization vector, a cryptographic nonce used to make different encryptions of the same plaintext generate different ciphertext. IV's are needed for all operation modes except ECB. See this wikipedia page for more details.