Příklad šifrování v Javě pomocí metody DES.
String phrase = “Your secret Key phrase”;
public String encrypt(String text) throws InvalidKeyException,
UnsupportedEncodingException, NoSuchAlgorithmException,
InvalidKeySpecException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException {
DESKeySpec keySpec = new DESKeySpec(phrase
.getBytes(“UTF8″));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(“DES”);
SecretKey key = keyFactory.generateSecret(keySpec);
sun.misc.BASE64Encoder base64encoder = new BASE64Encoder();
// ENCODE plainTextPassword String
byte[] cleartext = text.getBytes(“UTF8″);
Cipher cipher = Cipher.getInstance(“DES”); // cipher is not thread safe
cipher.init(Cipher.ENCRYPT_MODE, key);
return base64encoder.encode(cipher.doFinal(cleartext));
// now you can store it
}
public String decrypt(String s) throws IllegalBlockSizeException,
BadPaddingException, InvalidKeyException, InvalidKeySpecException,
NoSuchAlgorithmException, NoSuchPaddingException, IOException {
sun.misc.BASE64Decoder base64decoder = new BASE64Decoder();
// DECODE encryptedPwd String
byte[] encrypedPwdBytes = base64decoder.decodeBuffer(s);
DESKeySpec keySpec = new DESKeySpec(phrase
.getBytes(“UTF8″));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(“DES”);
SecretKey key = keyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance(“DES”);// cipher is not thread safe
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainTextPwdBytes = (cipher.doFinal(encrypedPwdBytes));
return new String(plainTextPwdBytes);
}