Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.security.InvalidKeyException;
- import java.security.NoSuchAlgorithmException;
- import javax.crypto.*;
- public class Encryption {
- private static SecretKey sKey;
- private Cipher objCipher;
- public Encryption () throws NoSuchAlgorithmException, NoSuchPaddingException {
- // Generate the secret key
- KeyGenerator generator = KeyGenerator.getInstance("DES");
- sKey = generator.generateKey();
- // Initialize the cipher instance to use DES algorithm, ECB mode,
- // and PKCS#5 padding scheme
- objCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
- //System.out.print("Algorithm => " + objCipher.getProvider());
- }
- public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
- String txt = "Here is the text";
- System.out.println("Plain text => " + txt);
- Encryption encrypt = new Encryption();
- //String enTxt = encrypt.encrypt(txt);
- byte[] enTxt = encrypt.encrypt(txt);
- String out_1 = new String(enTxt);
- System.out.println("Encrypted text => " + out_1);
- String deTxt = encrypt.decrypt(enTxt);
- System.out.println("Decrypted text => " + deTxt);
- }
- public byte[] encrypt (String txt) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
- // Initialize the cipher with secret key to decrypt data
- objCipher.init(Cipher.ENCRYPT_MODE,sKey);
- // Read the data into byte array
- byte[] text = txt.getBytes();
- // Store the encrypted data in a byte array
- byte[] encryptedData = objCipher.doFinal(text);
- return encryptedData;
- // Display the encrypted text in the textarea
- //String encryptedText = new String(encryptedData);
- //return encryptedText;
- }
- public String decrypt (byte[] txt) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
- // Initialize the cipher with secret key to decrypt data
- objCipher.init(Cipher.DECRYPT_MODE,sKey);
- // Read the encrypted data into byte array
- byte[] decryptedText = txt;
- // Store the decrypted data into byte array
- byte[] plainData = objCipher.doFinal(decryptedText);
- // Display the decrypted data in the textarea
- String plainText = new String(plainData);
- return plainText;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement