I want to encrypt/ decrypt with AES, with shared passwod, my code same as here.
the linked code works fine, but there is no shared passworn in it.
how can I add a shared password to the following implementation?
I need something like
String shared="xxx..";//some password with 16 digits length
Is it possible?
and adding this shared password to the encryption.
It is very important that the key used for AES encryption is not easy to guess so in a lot of implementations the keys are generated randomly. The key itself is a byte array of 16 (128 bit), 24 (192 bit) or 32 (256 bit) byte length and a byte array is not usuable as source for a shared password.
The solution is to encode the byte array into a Base64-encoded string and pass this string to the recepient on a secure way. The recepient decodes the string back to a byte array and further via the SecretKeySpec to a secret key.
The small example shows the way to securly generate a random password with different lengths (the example uses only the 128 bit keylength, encode it and decode it back to a secret key - the orginal SecretKey k is compared to the regenerated SecretKex kReceived.
Just a last notice but it is a security warning: Your encryption method is using the AES ECB mode that is unsecure - please do not use this mode in production (mode is defined here: AES/ECB/PKCS5Padding
).
Result:
https://stackoverflow.com/questions/62782129/encrypt-files-with-aes-with-shared-password
sharedKey: UT7PPJwX2fnYTazSOZAhxg==
keySpecReceived equals secretKey: true
Code:
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws NoSuchAlgorithmException {
System.out.println("https://stackoverflow.com/questions/62782129/encrypt-files-with-aes-with-shared-password");
// random key creation taken from https://stackoverflow.com/a/41414233/9114020
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = new SecureRandom();
int keyBitSize = 128; // aes keylength can be 128, 192 or 256 bit
keyGenerator.init(keyBitSize, secureRandom);
SecretKey k = keyGenerator.generateKey();
// encode the key and then base64-encoding
String sharedKey = Base64.getEncoder().encodeToString(k.getEncoded());
System.out.println("sharedKey: " + sharedKey);
// share this key with another party on a secure way
String sharedKeyReceived = sharedKey; // simulates the receiving
byte[] sharedKeyByteReceived = Base64.getDecoder().decode(sharedKeyReceived);
SecretKeySpec kReceived = new SecretKeySpec(sharedKeyByteReceived, "AES");
System.out.println("keySpecReceived equals secretKey: " + kReceived.equals(k));
}
}