'how to solve InvalidKeyException problem?
I encrypt my AES random key using RSA algorithm and public key, then I convert encoded bytes into secret key to encrypt my file, but an error occurred: Exception in thread "main" java.security.InvalidKeyException: Invalid AES key length: 256 bytes
this is my public key code:
public class keyGenerator {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
KeyPair pair = generator.generateKeyPair();
PrivateKey privateKey = pair.getPrivate();
PublicKey publicKey = pair.getPublic();
public keyGenerator() throws NoSuchAlgorithmException, FileNotFoundException, IOException, InvalidKeySpecException {
generator.initialize(2048);
try ( FileOutputStream fos = new FileOutputStream("private.key")) {
fos.write(privateKey.getEncoded());
}
}
}
and this is my AESEncryption method (NOTICE THAT cipherTxt.init(Cipher.ENCRYPT_MODE, sk); occurred the problem):
public static void AESEncryption(File in, File out) throws FileNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IllegalArgumentException, IOException, InvalidKeySpecException, GeneralSecurityException {
try {
//create GenerateKey object to accsess publicKey
private int KEY_SIZE = 128;
keyGenerator Key = new keyGenerator();
PublicKey pk = Key.publicKey;
//create random key
KeyGenerator g = KeyGenerator.getInstance("AES");
//give it size
g.init(KEY_SIZE);
//assign g.generateKey() to secretKey Randomkey
Randomkey = g.generateKey();
// encrypt the random key with RSA and public key
byte[] RandomByteKey = Randomkey.getEncoded();
Cipher cipherKey = Cipher.getInstance("RSA");
cipherKey.init(Cipher.ENCRYPT_MODE, pk);
byte[] encryptedKey = cipherKey.doFinal(RandomByteKey);//RSA key
SecretKey sk = new SecretKeySpec(encryptedKey, 0, encryptedKey.length, "AES");
//after generating RSA key we will Encrypt file using RSA key
Cipher cipherTxt = Cipher.getInstance("AES");
cipherTxt.init(Cipher.ENCRYPT_MODE, sk);
byte[] message = Files.readAllBytes(in.toPath());
byte[] encryptedMessage = cipherTxt.doFinal(message);
out.createNewFile();
Files.write(out.toPath(), encryptedKey);
Files.write(out.toPath(), encryptedMessage, StandardOpenOption.APPEND);
BufferedReader br = new BufferedReader(new FileReader("bla.bin"));
String line1;
while ((line1 = br.readLine()) != null) {
System.out.println(line1);
}
} catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException e) {
throw new RuntimeException("RSA or AES/GCM not available", e);
} catch (BadPaddingException e) {
throw new RuntimeException("Padding failed for NoPadding", e);
}
}
what should I do?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
