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
| import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang.StringUtils;
public class SymetricEncryptor {
private static String hexachars = "0123456789abcdef";
private static String TRANSFORMATION = "DESede/ECB/Nopadding";
private static String ALGORITHM = "DESede";
private static int SIZE_PWD = 16;
public static void main(String[] args) throws Exception {
String sInput = "123456789?;ABC";
String sInputAscii = toHex(sInput.getBytes());
sInputAscii = StringUtils.rightPad(sInputAscii, 2*SIZE_PWD, '0');
byte[] input = sInputAscii.getBytes();//"3132333435363738393F3B4142430000".getBytes();
byte[] theKey = "152618515457CD7A8C38160BB96B5D52152618515457CD7A".getBytes();
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
SecretKey secretKey = null;
SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM);
DESedeKeySpec ks = new DESedeKeySpec(theKey);
secretKey = skf.generateSecret(ks);
System.out.println("password : " + sInput);
System.out.println("password ASCII à crypter : " + sInputAscii);
// encryption pass
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
ctLength += cipher.doFinal(cipherText, ctLength);
System.out.println("password crypté: " + new String(cipherText) );
//String mdp = "1AAB8A8DEF38FBECF28219739DCEA300";
//cipherText = mdp.getBytes();
// decryption pass
SecretKey decryptionKey = new SecretKeySpec(secretKey.getEncoded(), secretKey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, decryptionKey);
byte[] plainText = new byte[cipher.getOutputSize(ctLength)];
int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);
ptLength += cipher.doFinal(plainText, ptLength);
System.out.println("password ASCII décrypté: " + new String(plainText));
}
public static String toHex(byte[] data, int length)
{
StringBuffer buf = new StringBuffer();
for (int i = 0; i != length; i++)
{
int v = data[i] & 0xff;
buf.append(hexachars.charAt(v >> 4));
buf.append(hexachars.charAt(v & 0xf));
}
return buf.toString();
}
public static String toHex(byte[] data)
{
return toHex(data, data.length);
}
} |
Partager