· 8 years ago · Dec 21, 2017, 07:40 PM
1package com.makotojava.crypto;
2
3import javax.crypto.spec.*;
4import java.security.*;
5import javax.crypto.*;
6
7public class Main
8{
9 static IvParameterSpec iv;
10
11 public static void main(String []args) throws Exception {
12 String toEncrypt = "Send $10 dollars to Eva Georgieva";
13
14 System.out.println("Encrypting...");
15 byte[] encrypted = encrypt(toEncrypt, "password");
16 //System.out.println("Encrypted text:" + encrypted);
17 System.out.println("Decrypting...");
18 String decrypted = decrypt(encrypted, "password");
19 //System.out.println("Decrypted text: " + decrypted);
20 System.out.println("Cut and paste: ");
21 cutAndPaste("Send $10 dollars to Eva Georgieva".getBytes());
22
23 }
24
25 public static void cutAndPaste(byte [] message) {
26 byte [] modifiedMessage = message;
27 byte b = 57;
28 modifiedMessage[6] = b;
29 System.out.println(new String(modifiedMessage));
30 }
31 public static byte[] encrypt(String toEncrypt, String key) throws Exception {
32 // create a binary key from the argument key (seed)
33 SecureRandom sr = new SecureRandom(key.getBytes());
34 KeyGenerator kg = KeyGenerator.getInstance("DES");
35 kg.init(sr);
36 SecretKey sk = kg.generateKey();
37
38 // create an instance of cipher
39 Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
40
41 // generate an initialization vector (IV)
42 SecureRandom secureRandom = new SecureRandom();
43 byte[] ivspec = new byte[cipher.getBlockSize()];
44 secureRandom.nextBytes(ivspec);
45 iv = new IvParameterSpec(ivspec);
46
47 // initialize the cipher with the key and IV
48 cipher.init(Cipher.ENCRYPT_MODE, sk, iv);
49
50 // encrypt!
51 byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
52
53 return encrypted;
54 }
55
56 public static String decrypt(byte[] toDecrypt, String key) throws Exception {
57 // create a binary key from the argument key (seed)
58 SecureRandom sr = new SecureRandom(key.getBytes());
59 KeyGenerator kg = KeyGenerator.getInstance("DES");
60 kg.init(sr);
61 SecretKey sk = kg.generateKey();
62
63 // do the decryption with that key
64 Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
65 cipher.init(Cipher.DECRYPT_MODE, sk, iv);
66 byte[] decrypted = cipher.doFinal(toDecrypt);
67
68 return new String(decrypted);
69 }
70}