convert Encryption Algo from C# to Java - java

public static string Encrypt(string KeyToEncrypt)
{
byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(KeyToEncrypt);
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(_Pwd, _Salt);
//Calling another private method for Encryption
byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
return Convert.ToBase64String(encryptedData);
}
private static byte[] Encrypt(byte[] candelaData, byte[] Key, byte[] IV)
{
MemoryStream ms = new MemoryStream();
CryptoStream cs = null;
Rijndael alg = Rijndael.Create();
alg.Key = Key;
alg.IV = IV;
cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(candelaData, 0, candelaData.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
I want to convert the following algo in java, I have searched for the libraries and couldn't get anything. Help Please. ?

Darab , your best bet in Java has to be Bouncy Castle. You have API's for crypt in salting as well as the AES Rijndael as i read from the code.
For the Rejndael part you can refer : http://www.itcsolutions.eu/2011/08/24/how-to-encrypt-decrypt-files-in-java-with-aes-in-cbc-mode-using-bouncy-castle-api-and-netbeans-or-eclipse/. This gives you a fair idea of the AES part of the code and this question here Rfc2898DeriveBytes in java gives you a great idea of salting and Rfc2898 as well.

Related

Private Key sign data in Java to PHP

I have to write PHP program to do the same function with the java sign function as follow
public static String sign(byte[] data, String privateKey) throws Exception {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(data);
byte[] hashData = messageDigest.digest();
StringBuffer hexString = new StringBuffer();
byte[] keyBytes = Base64Utils.decode(privateKey.getBytes());
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance("NONEWithRSA");
signature.initSign(privateK);
signature.update(hashData);
byte[] sign = signature.sign();
return Base64.getEncoder().encodeToString(sign);
}
I have done some research on google and try to write the PHP code as follow
public function sign($data, $privateKeyString){
$privateKey = openssl_pkey_get_private($privateKeyString);
$hashData = hash("sha256",$data);
openssl_sign($hashData, $signature, $privateKey);
openssl_free_key($privateKey);
return base64_encode($signature);
}
I try to pass the same key with the data let's say "Hello" to both function and testing
the hash data are map but the outcome signature are different
Is there anyone can spot what cause the return base64 signature are different between the java and php?
public function sign($data, $privateKeyString){
$privateKey = openssl_pkey_get_private($privateKeyString);
$hashData = openssl_digest("sha256",$data);
openssl_private_encrypt($hashData, $signature, $privateKey);
openssl_free_key($privateKey);
return base64_encode($signature);
}
Finally fixing the problem by using openssl_digest "sha256" instead of passing sha256 hash value into the for private key encrytion, due to the hashing need to be convert into the hex string instead of the original value.

Javascript Equivalent of Java AES+SecretKeySpec Decryption

Below is my java code which I am trying to move to NodeJS.
public static String decryptDataWithKey(String keyString, String base64String) throws Exception {
//Algorithm
String AES_ALGORITHM = "AES";
//Key from keystring
MessageDigest digester = MessageDigest.getInstance("MD5");
digester.update(keyString.getBytes());
byte[] password = digester.digest();
Key key = new SecretKeySpec(password, AES_ALGORITHM); // what is the equivalent of this line in javascript ?
//Create decipher
Cipher c = Cipher.getInstance(AES_ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
//Get bytes of enc data
byte[] decodedValue = new BASE64Decoder().decodeBuffer(base64String);
// Do decrypt
byte[] decValue = c.doFinal(decodedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
I ended up writing below method, but getting exception - Bad Decrypt
function decryptDataWithKey(keyString, base64String){
//Algorithm
let algorithm = 'aes-128-ecb';
//Key from keystring
let key = crypto.createHash('md5').update(keyString).digest();
//Create decipher
let decipher = crypto.createDecipher(algorithm,key);
//Get bytes of enc data
let cipher = new Buffer(base64String, 'base64');
// Do decrypt
let decrypted = decipher.update(cipher, 'base64', 'utf-8');
decrypted += decipher.final('utf-8'); // throwing exception : digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
return decrypted;
}
Please guide me what I am missing here. I am trying to avoid the jar dependency in my nodejs project. I believe this should be achievable using crypto.
Or Should I go for crypto-js ?

How do I translate this C# encrypt function into Java?

I need to translate the below C# codes into Java, however, I could not find any Java equivalent to the Rfc2898DerivedBytes and Rijndael of C#.
private static string Encrypt(string sData, string sEncryptionKey)
{
string str = null;
string str2;
try
{
Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(sEncryptionKey, 8);
Rijndael rijndael = Rijndael.Create();
rijndael.IV = bytes.GetBytes(rijndael.BlockSize / 8);
rijndael.Key = bytes.GetBytes(rijndael.KeySize / 8);
byte[] buffer = Encoding.Unicode.GetBytes(sData);
using (MemoryStream stream = new MemoryStream())
{
using (CryptoStream stream2 = new CryptoStream(stream, rijndael.CreateEncryptor(), CryptoStreamMode.Write))
{
stream.Write(bytes.Salt, 0, bytes.Salt.Length);
stream2.Write(buffer, 0, buffer.Length);
stream2.Close();
str = Convert.ToBase64String(stream.ToArray());
str2 = str;
}
}
}
catch (Exception exception)
{
System.out.println(exception.getMessage());
}
return str2;
}
[Update]
I need to use this function to encrypt the password for new created user, and the encrypted password should also be correctly decrypted by other invoker including C#.
I follow the documents which list in the comments and answer, and try to write below simply sample for quickly verification.
public class testEncrypt {
public static void main(String[] args) throws Exception {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
char[] password = "passkey".toCharArray();
SecureRandom random = new SecureRandom();
byte[] salt = new byte[8];
random.nextBytes(salt);
KeySpec spec = new PBEKeySpec(password, salt, 1000, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] ciphertext = cipher.doFinal("301a7fed-54e4-4ae2-9b4d-6db057f75c91".getBytes("UTF-8"));
System.out.println(ciphertext.length);
}
}
However, the length of the ciphertext is 48, but actually in C#, it looks like this format
WHUNV5xrsfETEiCwcT0M731+Ak1jibsWEodJSaBraP1cmmkS1TpGWqwt/6p/a7oy8Yq30ImZPbFF+Y0JNLa3Eu2UGuazZtuhEepUIIdaDEtA2FO0JYIj2A==
total 120 characters.
Is there something wrong with the code?
RFC2898 is the official name for PBKDF2 (Password Based Key Derivation Function).
This question seems to use the SecretKeyFactory class for PBKDF2.
Password Verification with PBKDF2 in Java
If you cannot find any implementation that you are satisfied with, I suggest you take a look at my question where I used a few classes from BouncyCastle (for C#, but should work for Java) and created the algorithm. I had to create this for C# because there was no Rfc2898DeriveBytes for the .NET Compact Framework.
This question should definitely help you too!
You can also find an implementation here that was done by someone who stumbled across your same problem.
Also to answer the second part of your question,
Rijndael doesn't differ much from AES. To quote this webpage
Namely, Rijndael allows for both key and block sizes to be chosen
independently from the set of { 128, 160, 192, 224, 256 } bits. (And
the key size does not in fact have to match the block size). However,
FIPS-197 specifies that the block size must always be 128 bits in AES,
and that the key size may be either 128, 192, or 256 bits.
Rijndael algorithm was chosen by the NIST to be the Advanced Encryption algorithm.
So you can use the AES algorithm in Java.

Decrypt AES encrypted file in java

I have a file encrypted with java application using AES. I also have a key file was encrypted with. But i can't understand how to use the key to decrypt file. Most tutorials and examples create temporary random key, encrypt file and decrypt it in one place.
So, question is how to specify a key which have to be used for decryption?
EDIT:
Samples i found use following code to generate key. I have no idea where i can use my key here.
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
Just to summarise my comments to Lucifer's answer.
If you don't know what padding was used to encrypt, then decrypt with 'no padding' set. That will decrypt everything, including the padding, and won't throw an error because of mismatched padding.
When you have decrypted the cyphertext, have a look at the last block of the output and see what padding was used. Different paddings leave different byte patterns, so it is usually easy enough to tell.
Set your decryption method to expect the correct type of padding, and it will be automatically removed for you.
The answer could be simply to put the key data as bytes into a SecretKeySpec like this:
SecretKeySpec aesKey = new SecretKeySpec(myKeyData, "AES");
Note that SecretKeySpec implements the Key interface, so you can use it directly in a Cipher.init() method. So there is no SecretKeyFactory needed, which you would use otherwise.
Please try following methods, if might helpful for you.
private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data)
throws Exception
{
int minSize = cipher.getOutputSize(data.length);
byte[] outBuf = new byte[minSize];
int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
int length2 = cipher.doFinal(outBuf, length1);
int actualLength = length1 + length2;
byte[] result = new byte[actualLength];
System.arraycopy(outBuf, 0, result, 0, result.length);
return result;
}
private static byte[] decrypt(byte[] cipher, byte[] key, byte[] iv) throws Exception
{
PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
new AESEngine()));
CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
aes.init(false, ivAndKey);
return cipherData(aes, cipher);
}
private static byte[] encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception
{
PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
new AESEngine()));
CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
aes.init(true, ivAndKey);
return cipherData(aes, plain);
}
Complete example of encrypting/Decrypting a huge video without throwing Java OutOfMemoryException and using Java SecureRandom for Initialization Vector generation. Also depicted storing key bytes to database and then reconstructing same key from those bytes.
https://stackoverflow.com/a/18892960/185022

3DES - Decrypt encrypted text (by JAVA) in C#

Here is the situation:
The encrypted text is done in JAVA (which we have no JAVA background at all)
The method is 3DES
The padded is PKCS#5
Base 64
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));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToDecrypt = Convert.FromBase64String(Message);
try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return UTF8.GetString(Results);
}
However, when tried to decrypt, got the error message: BAD DATA
Where am I missing here?
Thanks in advance.
Added, and here's how the encryption works:
<cffunction name="getToken" returntype="String" output="false">
<cfscript>
plainText = getPlainText();
rawSecretKey = CreateObject("java","sun.misc.BASE64Decoder").decodeBuffer(variables.encryptionKey);
secretKeySpec = CreateObject("java","javax.crypto.spec.SecretKeySpec").init(rawSecretKey,"DESEDE");
cipher = CreateObject("java","javax.crypto.Cipher").getInstance("DESEDE");
cipher.init(Cipher.ENCRYPT_MODE, secretkeySpec);
encrypted = cipher.doFinal(plainText.getBytes()); // a byte array (a binary in CF)
return URLEncodedFormat(ToString(ToBase64(encrypted)));
</cfscript>
</cffunction>
Update:
This issue has been resolved. The problem was that the key needed to be converted from Base64.
The answer:
Instead of:
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
Do this:
byte[] TDESKey = Convert.FromBase64String(Passphrase);
That solves this issue.

Categories