Guest User

Untitled

a guest
Feb 21st, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.86 KB | None | 0 0
  1.     public static String EncryptString(String plaintext, String password) throws Exception{
  2.         // Create Key
  3.         byte key[] = password.getBytes();
  4.         DESKeySpec desKeySpec = new DESKeySpec(key);
  5.         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
  6.         SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
  7.  
  8.         // Create Cipher
  9.         Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
  10.         desCipher.init(Cipher.ENCRYPT_MODE, secretKey);
  11.        
  12.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  13.         CipherOutputStream cos = new CipherOutputStream(baos, desCipher);
  14.        
  15.         cos.write(plaintext.getBytes());
  16.         cos.flush();
  17.         cos.close();
  18.         return baos.toString();
  19.     }
  20.  
  21.     public static String DecryptString(String encryptedText, String password) throws Exception{
  22.         // Create Key
  23.         byte key[] = password.getBytes();
  24.         DESKeySpec desKeySpec = new DESKeySpec(key);
  25.         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
  26.         SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
  27.  
  28.         // Create Cipher
  29.         Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
  30.         desCipher.init(Cipher.DECRYPT_MODE, secretKey);
  31.  
  32.         ByteArrayInputStream bais = new ByteArrayInputStream(encryptedText.getBytes());
  33.         CipherInputStream cis = new CipherInputStream(bais, desCipher);
  34.        
  35.         byte[] read = new byte[desCipher.getOutputSize(encryptedText.getBytes().length)];
  36.         cis.read(read, 0, read.length);
  37.         cis.close();
  38.        
  39.         return new String(read);
  40.     }
  41.  
  42.     public static void main(String args[]) throws Exception {
  43.         String plain = "Some DUDE thought he had swagger, but he didn't!";
  44.         System.out.println("Encrypting: " + plain);
  45.         String enc = EncryptString(plain, SymmetricCrypt.password);
  46.         System.out.println("Result: " + enc);
  47.         String dec = Decrypt.DecryptString(enc, SymmetricCrypt.password);
  48.         System.out.println("Decrypted to: " + dec);
  49.     }
Add Comment
Please, Sign In to add comment