Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
suppose you ask user to generate public_key using JPasswordField and then you should take this public_key to encrypt random_key what should I do?

What I have tried:

Java
public void AESEncryption(File file) throws FileNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    String data;
    SecretKey random_key;
    int key_size=128;

    Scanner myReader = new Scanner(file);
    while (myReader.hasNextLine()) {
        data = myReader.nextLine();
    }

    // create GenerateKey object to access public key
    // GenerateKey is my personal class and contain public key that generated from user using JPasswordField
    GenerateKey key = new GenerateKey();

    // convert public key to string
    String public_Key = key.PublicKey.getText();

    // convert string public key to secret key
    byte[] decodedKey = Base64.getDecoder().decode(public_Key);
    SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");

    // generate random key
    KeyGenerator g = KeyGenerator.getInstance("AES");
    // give it size
    g.init(key_size);
    random_key = g.generateKey();

    // encrypt the random key with RSA and public key
    byte[] random_byteKey = random_key.getEncoded();
    Cipher cipher_Key = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher_Key.init(Cipher.ENCRYPT_MODE, originalKey);
    byte[] encrypted_key = cipher_Key.doFinal(random_byteKey); //RSA key

    // after generating RSA key we will Encrypt file using RSA key
    byte[] byte_message = data.getBytes();
    Cipher cipherTxt = Cipher.getInstance("AES/GCM/NoPadding");
    // the problem in here 
    cipherTxt.init(Cipher.ENCRYPT_MODE, encrypted_key);

    byte[] encByte = cipherTxt.doFinal(byte_message);
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900