Advertisement
top_wizard

SymmetricApp class

Dec 11th, 2014
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.70 KB | None | 0 0
  1. package javaapplication1;
  2. import java.security.*;
  3. import javax.crypto.*;
  4.  
  5. public class SymmetricApp {
  6.     public void demoEncryption(){
  7.         try {
  8.             String message = "Selamat datang Java";
  9.             byte[] plainText = message.getBytes("UTF8");
  10.             //get a DES private key
  11.             System.out.print("Generating DES key...");
  12.             KeyGenerator keyGen = KeyGenerator.getInstance("DES");
  13.             keyGen.init(56);
  14.             Key key = keyGen.generateKey();
  15.             System.out.println("Done");
  16.             //get a DES cipher object and print the provider
  17.             Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
  18.             //encypt using the key and the plaintext
  19.             System.out.printf("Encryption...");
  20.             cipher.init(Cipher.ENCRYPT_MODE,key);
  21.             byte[] cipherText = cipher.doFinal(plainText);
  22.             System.out.println("Done");
  23.             // decrypt the ciphertext using the same key
  24.             System.out.print ("Decryption...");
  25.             cipher.init(Cipher.DECRYPT_MODE, key);
  26.             byte[] newPlainText=cipher.doFinal(cipherText);
  27.             System.out.println("Done");
  28.             System.out.println("Message: "+message);
  29.             System.out.println("Encrypted: "+new String(cipherText,"UTF8"));
  30.             System.out.println("Encrypted Hex: "+StringUtils.getHexString(cipherText));
  31.             System.out.println("Plaintex: "+new String (newPlainText,"UTF8"));
  32.         }catch (Exception e){
  33.             System.out.println("Error: "+e.getMessage());
  34.         }
  35.     }
  36.     public static void main(String[] args) {
  37.         SymmetricApp app=new SymmetricApp();
  38.         app.demoEncryption();
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement