If you want to encrypt files, lines, etc., there are two main approaches. You should start by creating a class or method to convert ur string / file to an array of bytes. Build another way to convert an array of bytes into a string / file.
You can encrypt a file using two approaches: 1 - Symmetric key. The secret word (usually a huge string of characters or a password set by the user) will encrypt your file and password, and the same password will be used for decryption. 2 - Asymmetric key - you create a key pair. One of them is called the public key, and the other is called the private key. Public keys are used to encrypt files, private keys to decrypt. This will be a more βprofessionalβ approach.
If you need a truly secure approach, you should download GnuPG. GnuPG is an executable file that controls asymmetric encryption, you can create a class to work with GnuPG and let GnuPG control the ur encryption / decryption process.
Theres an unsafe approach that is "native" to java (symmetric key), which might work for you:
Encryption:
byte[] key = //... password converted to an array of bytes byte[] dataToSend = ... Cipher c = Cipher.getInstance("AES"); SecretKeySpec k = new SecretKeySpec(key, "AES"); c.init(Cipher.ENCRYPT_MODE, k); byte[] encryptedData = c.doFinal(dataToSend);
decryption:
byte[] key = // byte[] encryptedData = // Cipher c = Cipher.getInstance("AES"); SecretKeySpec k = new SecretKeySpec(key, "AES"); c.init(Cipher.DECRYPT_MODE, k); byte[] data = c.doFinal(encryptedData);
Hope this helps.
source share