1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
|
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.SecretKeySpec;
public class PrivateExample{
protected static String crypting(String textToCrypting, String keyString ) {
Cipher cipher = null;
try {
cipher = Cipher.getInstance("DES");
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
} catch (NoSuchPaddingException ex) {
ex.printStackTrace();
}
byte[] keyData = keyString.getBytes();
SecretKeySpec key = new SecretKeySpec(keyData, 0, keyData.length, "DES");
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
} catch (InvalidKeyException ex) {
ex.printStackTrace();
}
int cypheredBytes = 0;
byte[] inputBytes = textToCrypting.getBytes();
byte[] outputBytes = new byte[100];
try {
cypheredBytes = cipher.doFinal(inputBytes, 0, inputBytes.length, outputBytes, 0);
} catch (IllegalStateException ex) {
ex.printStackTrace();
} catch (ShortBufferException ex) {
ex.printStackTrace();
} catch (IllegalBlockSizeException ex) {
ex.printStackTrace();
} catch (BadPaddingException ex) {
ex.printStackTrace();
}
String str = new String(outputBytes, 0, cypheredBytes);
inputBytes = str.getBytes();
return str;
}
protected static String decrypting(String textCrypting, String keyString ) {
cipher = Cipher.getInstance("DES");
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
} catch (NoSuchPaddingException ex) {
ex.printStackTrace();
}
//The lenght of keyString is 8. It's important characteristic
//for encryption
byte[] keyData = keyString.getBytes();
//key object specifies a secret key
//it uses to construct the secret key for our cipher object from a byte
//array
SecretKeySpec key = new SecretKeySpec(keyData, 0, keyData.length, "DES");
try {
//change state of the cipher object for decrypting
cipher.init(Cipher.DECRYPT_MODE, key);
} catch (InvalidKeyException ex) {
ex.printStackTrace();
}
int cypheredBytes = 0;
byte[] inputBytes = textCrypting.getBytes();
byte[] outputBytes = new byte[1000];
try {
//decrypts data
cypheredBytes = cipher.doFinal(inputBytes, 0, inputBytes.length,
outputBytes, 0);
} catch (IllegalStateException ex) {
} catch (ShortBufferException ex) {
} catch (IllegalBlockSizeException ex) {
} catch (BadPaddingException ex) {
}
String str = new String(outputBytes, 0, cypheredBytes);
return str;
}
} |