I am writing a crypter application on java for a school project (you can even say a newbie), I want to implement the RSA algorithm so that you can pass the secret key from AES through to the “interlocutor”. Here is the code of the encryption method. pubKey and priKey are already implemented and automatically generated. The string strOpenTextE is sent to the input and I want to be able to transmit the encrypted message via any social messenger network, for this, I make the asString byte array from a string on the Base64 encoding, but a problem immediately appears. Base64.Decoder sometimes does not read duplicate letters, or even adds its own bytes because of which the source text is distorted after decryption. I do not know what to do. Other encodings give an incomprehensible set of characters that is not even decrypted, and this encoding gives a string of Latin letters and symbols that can be just conveyed to the interlocutor as a string. I would be glad if someone tells you how to make the source text encrypted in a string, and then decrypted without errors.
private static void Shifrated() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException, IOException { cipher = Cipher.getInstance("RSA"); if (mode == 1) { cipher.init(Cipher.ENCRYPT_MODE, pubKey); byte[] asString = new sun.misc.BASE64Decoder().decodeBuffer(strOpenTextE); byte[] bytes = cipher.doFinal(asString); strCipherE = new sun.misc.BASE64Encoder().encode(bytes); } else if (mode == 2) { cipher.init(Cipher.DECRYPT_MODE, priKey); byte[] asString = new sun.misc.BASE64Decoder().decodeBuffer(strCipherD); byte[] bytes1 = cipher.doFinal(asString); strOpenTextD = new sun.misc.BASE64Encoder().encode(bytes1);; } @ FXML // controller code that encrypts the message void useMethod (ActionEvent event) {
RsaCreate.setPublicKey(friendKey.getText()); //friendkey - TextField с публичным ключом RsaCreate.madePubKey(); RsaCreate.setStrOpenTextE(yourKey.getText()); //yourKey - TextField с сообщением, которое надо зашифровать RsaCreate.setMode(1); RsaCreate.Start(); getKey.setText(RsaCreate.getStrCipherE()); } @ FXML // code that decrypts the message void mouse (Event event) {
if(!newFriendKey.getText().equals("")) { RsaCreate.setStrCipherD(newFriendKey.getText()); //newFriendKey - TexField с зашифрованной строкой RsaCreate.setMode(2); RsaCreate.Start(); profileKey.setText(RsaCreate.getStrOpenTextD()); } Tell me what I'm doing wrong (