I'm trying to encrypt and decrypt some texts using Cipher with the "AES/CBC/PKCS5Padding" algorithm but if I restart the application the text that was encrypt can't be decrypted.
I'm encrypting the text, transforming the encrypted bytes in base64 text, storing it and retrieving it when necessary, so transforming the base64 text in bytes and trying to decrypt to take the original text.
The code I'm using is:
private static SecretKey getKeyFromPassword(String password, String salt)
throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(UTF_8),
65536, 256);
SecretKey secret = new SecretKeySpec(factory.generateSecret(spec)
.getEncoded(), "AES");
return secret;
}
private static IvParameterSpec generateIv() {
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);
return new IvParameterSpec(iv);
}
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
// string for test
String teste = "teste teste teste teste";
//getting start with Cipher
SecretKey secretKey = getKeyFromPassword("pass", "salt");
IvParameterSpec ivParameterSpec = generateIv();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//encrypting
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
byte[] cipherText = new byte[0];
cipherText = cipher.doFinal(teste.getBytes(UTF_8));
// encrypt to base64 text
String criptado = Base64.getEncoder().encodeToString(cipherText);
//decripting
byte[] plainText = new byte[0];
byte[] rawText = Base64.getDecoder().decode(criptado);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
plainText = cipher.doFinal(rawText);
String decriptado = new String(plainText);
The problem is something with the size of the bit key? Like in this topic: java AES/CBC/PKCS5PADDING in php (AES-256-CBC) resulting different result
I took this guide to the code: baeldung.com/java-aes-encryption-decryption
Related
I have been trying to send data effectively between two applications. One is implemented in C# (Sender) the other in Java (Receiver). The sender has to encrypt data using the transformation "AES/GCM/NOPadding" with a 32-byte key while the receiver has to decrypt using the same parameters. Here is the sender encryption function in C# (using bouncy castle)
public static string Encrypt(string plainText, string msgId)
{
const byte GcmTagSize = 16;
byte[] hashKey;
byte[] secretKey = Encoding.UTF8.GetBytes(msgId);
Console.WriteLine(secretKey.Length);
using (var hasher = SHA512.Create())
{
byte[] digestSeed = hasher.ComputeHash(secretKey);
hashKey = new byte[16];
Array.Copy(digestSeed, hashKey, hashKey.Length);
}
var keyParameter = new KeyParameter(hashKey);
var keyParameters = new AeadParameters(keyParameter, GcmTagSize * 8, secretKey);
var cipher = CipherUtilities.GetCipher("AES/GCM/NoPadding");
cipher.Init(true, keyParameters);
var plainTextData = Encoding.ASCII.GetBytes(plainText);
var cipherText = cipher.DoFinal(plainTextData); //bouncy castle
return Convert.ToBase64String(cipherText);
}
Here is the receiver decryption function in java
private static byte[] decrypt(byte[] message, SecretKey key) throws NoSuchPaddingException, NoSuchAlgorithmException,
IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, InvalidKeyException {
Cipher cipher = Cipher.getInstance("AES/GCM/NOPadding"); //NoPadding
byte[] nonce = Arrays.copyOfRange(message, message.length - cipher.getBlockSize(), message.length);
byte[] encryptedKycData = Arrays.copyOf(message, message.length - cipher.getBlockSize());
System.out.println(doEncode(nonce));
System.out.println(doEncode(nonce));
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, nonce);
cipher.init(Cipher.DECRYPT_MODE, key, gcmParameterSpec);
byte[] decryptedValue=cipher.doFinal(encryptedKycData);
return decryptedValue;
}
When I try to decrypt with the java decryption function I get the error
javax.crypto.AEADBadTagException: Tag mismatch
Struggling with this issue and any help would be appreciated.
First, please excuse my bad english, this is not my native language.
i am trying to encode and then decode some text of different lengths.
I tried to encode some text with RSA algorithm in java. In the progress, I found out that RSA-encoding is limited to a specific size of bytes, so this approach doesn't fit my specs as my text could be large.
As I want to stay with a public and a private key only, I came up with the idea to use a 'hard-coded' AES key which will be encoded with RSA public key and than use this to encode the data. (see code)
//harcoded secretkey base64 encoded
private static final String secretkey_base64 = "xtnN6Pove5AovbLXtGRJKw==";
//this is how RSA key are generated
public static KeyPair genKeys() throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance( "RSA" );
kpg.initialize(2048);
KeyPair kp = kpg.generateKeyPair();
return kp;
}
//here text should be encoded
public static String encodeText(String plainText, PublicKey publicKey) throws Exception
{
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherText = encryptCipher.doFinal(CryptoUtil.secretkey_base64.getBytes(UTF_8));
String encodedSecKey = Base64.getEncoder().encodeToString(cipherText);
SecretKeySpec k = new SecretKeySpec(Base64.getDecoder().decode(encodedSecKey), "AES");
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, k);
byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(byteCipherText);
}
Obviously this doesn't work because the RSA encoded AES key is too long for AES encryption. Throws "Invalid AES key length: 256 bytes"
Does anyone have an idea how I could get the encryption running with this particular approach ?
Is this even possible, or do I have to use a different approach?
Thanks in advance.
//edit - Solved thanks to #ewramner
// here is the working solution:
public static String encodeText(String plainText, PublicKey publicKey) throws Exception
{
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128); // The AES key size in number of bits
SecretKey secKey = generator.generateKey();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.PUBLIC_KEY, publicKey);
byte[] encSecKey = cipher.doFinal(secKey.getEncoded());
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encSecKey) + "#" + Base64.getEncoder().encodeToString(byteCipherText);
}
public static String decodeText(String cipherText, PrivateKey privateKey) throws Exception
{
String[] split = cipherText.split("#");
String encSecKey = split[0];
String encText = split[1];
byte[] bytesSecKey = Base64.getDecoder().decode(encSecKey);
byte[] bytesText = Base64.getDecoder().decode(encText);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.PRIVATE_KEY, privateKey);
byte[] decSecKey = cipher.doFinal(bytesSecKey);
SecretKey secKey = new SecretKeySpec(decSecKey , 0, decSecKey .length, "AES");
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.DECRYPT_MODE, secKey);
return new String(aesCipher.doFinal(bytesText));
}
I want to use JAVA encryption and decryption logic in qt creator code i tried and search lot of stuff but success for "DES/CBC" Encryption and Decryption Logic but not useful for me Because JAVA code is in "DESede/CBC/PKCS5Padding" Triple DES logic.
JAVA CODE is as follows:
public static String initializationVector = "abhijeet";
public static String key="XB13347FE570DC4FFB13647F";
public String encryptText(String plainText) throws Exception {
// ---- Use specified 3DES key and IV from other source --------------
byte[] plaintext = plainText.getBytes();
byte[] tdesKeyData = Config.key.getBytes();
// byte[] myIV = initializationVector.getBytes();
Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
IvParameterSpec ivspec = new IvParameterSpec(Config.initializationVector.getBytes());
c3des.init(Cipher.ENCRYPT_MODE, myKey, ivspec);
byte[] cipherText = c3des.doFinal(plaintext);
return new BASE64Encoder().encode(cipherText);
}
public static String decryptText(String cipherText) throws Exception {
byte[] encData = new BASE64Decoder().decodeBuffer(cipherText);
Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
byte[] tdesKeyData = Config.key.getBytes();
SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
IvParameterSpec ivspec = new IvParameterSpec(Config.initializationVector.getBytes());
decipher.init(Cipher.DECRYPT_MODE, myKey, ivspec);
byte[] plainText = decipher.doFinal(encData);
return new String(plainText);
}
Example :
Input string - "Hello"
After Encryption Output string - "c13FZpr4odg="
Please Help for the same as i stuck here
I am using AESCrypt (gradle :compile 'com.scottyab:aescrypt:0.0.1')
to encrypt and decrypt the data.
TextView tv=(TextView)findViewById(R.id.demotext);
String encrypted="",decrypted="";
try {
encrypted = AESCrypt.encrypt("password","This is the best thing to go by");
decrypted = AESCrypt.decrypt("password",encrypted);
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
System.out.println("EncryptedData:"+encrypted);
System.out.println("DecryptedData:"+decrypted);
tv.setText("Encrypted:"+encrypted +"\n"+"Decrypted:"+decrypted);
The code works perfectly fine in this case, I get the same input as decrypted text.
But, when I try to use already encrypted string using the same method (AES) from the site http://aesencryption.net/ as shown in the screenshot:
And copy paste that encrypted text like:
decrypted = AESCrypt.decrypt("password","sttA+FbNm3RkTovjHI8CcAdStXiMl45s29Jqle+y+pA=");
And then run the code then I get error saying :
javax.crypto.BadPaddingException: error:1e06b065:Cipher functions:EVP_DecryptFinal_ex:BAD_DECRYPT
But when I use the decrypted text into the same site it works fine as shown in the screenshot below.
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;
}
Probably due to the algorithm to convert the passphrase 'password' to SecretKeySpec
This is the algorithm in AESCrypt
private static SecretKeySpec GenerateKey (final String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
final MessageDigest digest = MessageDigest.getInstance (HASH_ALGORITHM);
byte [] bytes = password.getBytes ("UTF-8");
digest.update (bytes, 0, bytes.length);
byte [] key = digest.digest ();
log ("SHA-256 key" key);
SecretKeySpec secretKeySpec = new SecretKeySpec (key, "AES");
secretKeySpec return;
}
And this is the (Java) example aesencryption.net
sha = MessageDigest.getInstance ("SHA-1");
key = sha.digest (key);
key = Arrays.copyOf (key, 16); // Use only first 128 bit
SecretKey = new SecretKeySpec (key, "AES");
The first one applies SHA256 hashing, and the second SHA-1 after completing up to 16 bytes, so the key is different.
I think you are encrypting and decrypting AES in the right way. You do not need to change anything.
But if you want to be compatible with aesencryption.net, you need to implement the same key generation algorithm. The code is not too good. I try to summarize
//Code from aesencryption.net
// Generate key
MessageDigest sha = null;
key = myKey.getBytes ("UTF-8");
sha = MessageDigest.getInstance ("SHA-1");
key = sha.digest (key);
key = Arrays.copyOf (key, 16); // Use only first 128 bit
SecretKey = new SecretKeySpec (key, "AES");
public static String encrypt (String strToEncrypt) {
Cipher cipher = Cipher.getInstance ("AES / ECB / PKCS5Padding");
cipher.init (Cipher.ENCRYPT_MODE, SecretKey);
Base64.encodeBase64String return (cipher.doFinal (strToEncrypt.getBytes ("UTF-8"))));
}
public static String decrypt (String strToDecrypt) {
Cipher cipher = Cipher.getInstance ("AES / ECB / PKCS5PADDING");
cipher.init (Cipher.DECRYPT_MODE, SecretKey);
return new String (cipher.doFinal (Base64.decodeBase64 (strToDecrypt))));
}
I can also provide my own code extracted from an Android app witch requires to store private user data. Data is ciphered with an AES key protected with an user passphrase
public static String SIMMETRICAL_ALGORITHM = "AES";
//Generate cipher key with user provided password
private static String getPassphraseSize16(String key) {
if (TextUtils.isEmpty(key)) {
return null;
}
char controlChar = '\u0014';
String key16 = key + controlChar;
if (key16.length() < 16) {
while (key16.length() < 16) {
key16 += key + controlChar;
}
}
if (key16.length() > 16) {
key16 = key16.substring(key16.length() - 16, key16.length());
}
return key16;
}
//AES cipher with passphrase
public static byte[] encrypt(byte[] message, String passphrase)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
String passphrase16 = getPassphraseSize16(passphrase);
SecretKeySpec secretKey = new SecretKeySpec(passphrase16.getBytes(), SIMMETRICAL_ALGORITHM);
Cipher cipher = Cipher.getInstance(SIMMETRICAL_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encoded = cipher.doFinal(message);
return encoded;
}
//AES decipher with passphrase
public static byte[] decrypt(byte[] encodedMessage, String key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
String passphrase16 = getPassphraseSize16(key);
SecretKeySpec secretKey = new SecretKeySpec(passphrase16.getBytes(), SIMMETRICAL_ALGORITHM);
Cipher cipher = Cipher.getInstance(SIMMETRICAL_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte decoded[] = cipher.doFinal(encodedMessage);
return decoded;
}
I need to implement an encryption and decryption method pair using C# that uses "AES/ECB/PKCS5Padding". The original code is in Java. Here is the encryption method in Java:
public static String Encrypt(String plainText, byte[] key2) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
byte[] encryptedTextBytes=null;
byte[] key3 =null;
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key3= sha.digest(key2);
key3 = copyOf(key3, 16);
SecretKeySpec keySpec = new SecretKeySpec(key3, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
return new Base64().encode(encryptedTextBytes);
}
And this is my attempt at reconstructing it in C#:
public static string Encrypt_AES(string plainText, byte[] key2)
{
var sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
byte[] key3 = new byte[16];
sha.TransformFinalBlock(key2, 0, key2.Length);
var tmpkey = sha.Hash;
Array.Copy(tmpkey, key3, 16);
var aes = new System.Security.Cryptography.AesCryptoServiceProvider();
aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
aes.Mode = System.Security.Cryptography.CipherMode.ECB;
aes.Key = key3;
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
var encryptor = aes.CreateEncryptor();
byte[] encryptedTextBytes = encryptor.TransformFinalBlock(plainTextBytes, 0, plainTextBytes.Length);
return Convert.ToBase64String(encryptedTextBytes);
}
After encrypting some content and sending it to a remote service, the service replies with an error saying that it could not decrypt the message. So I'm assuming something is wrong with it.
I also have an example for a decrypt method in Java. I implemented that method too and tried to encrypt and decrypt some text locally. When I do that, the Decrypt_AES method is throwing a CryptographicException at TransformFinalBlock() saying "Padding is invalid and cannot be removed." Maybe I'm using the CryptoProvider classes wrong?
Here are the Java and C# versions of the decrypt function:
Java
public static String Decrypt(String encryptedText, byte[] key2) throws NoSuchAlgorithmException,NoSuchPaddingException,InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
byte[] decryptedTextBytes=null;
byte[] key3 =null;
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key3= sha.digest(key2);
key3 = copyOf(key3, 16);
SecretKeySpec keySpec = new SecretKeySpec(key3, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] encryptedTextBytes = new Base64().decode(encryptedText);
decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
return new String(decryptedTextBytes);
}
C#
public static string Decrypt_AES(byte[] key2, string encryptedText)
{
var sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
byte[] key3 = new byte[16];
sha.TransformFinalBlock(key2, 0, key2.Length);
var tmpkey = sha.Hash;
Array.Copy(tmpkey, key3, 16);
var aes = new System.Security.Cryptography.AesCryptoServiceProvider();
aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
aes.Mode = System.Security.Cryptography.CipherMode.ECB;
aes.Key = key3;
var encryptedBytes = Encoding.UTF8.GetBytes(encryptedText);
var decryptor = aes.CreateDecryptor();
var decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
return System.Text.Encoding.UTF8.GetString(decryptedBytes);
}
Thank you for any hint in advance!
You are not Base64-decoding your ciphertext in your decrypt method.
var encryptedBytes = Encoding.UTF8.GetBytes(encryptedText);
should be changed to something like
var encryptedBytes = Convert.FromBase64String(encryptedText);