Thursday

Encrypt/Decrypt string with DES algorithm in java

public static void main(String[] args) throws Exception {
           
            byte[] message = "Give your text to encrypt.".getBytes();
            byte[] keyValue = "YourOwnKey".getBytes();
           
            Cipher cipher = Cipher.getInstance("DES");
            DESKeySpec dks = new DESKeySpec(keyValue);
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            SecretKey desKey = skf.generateSecret(dks);
           
            cipher.init(Cipher.ENCRYPT_MODE, desKey);
            byte[] textEncrypted = cipher.doFinal(message);
            String encrypted = DatatypeConverter.printBase64Binary(textEncrypted);
            System.out.println("Text Encrypted : " + encrypted);
           
            cipher.init(Cipher.DECRYPT_MODE, desKey);
            byte[] texDecrypted = cipher.doFinal(textEncrypted);
            System.out.println("Text Decryted : " + new String(texDecrypted) );
           
      }

No comments:

Post a Comment