Con questo post inauguro la sezione di programmazione, in cui inserirò frammenti di codice utili per la risoluzione di alcuni problemi che ho riscontrato nel mio lavoro (con le relative fonti).
Il codice seguente, come tutto quello scritto nel blog può essere utilizzato liberamente ed è da intendersi senza garanzia. Insomma, non prendetevela con me se quello che ho scritto non funziona e/o vi ha incasinato il sistema.
Premesso questo, ecco un esempio di codice scritto in Java che permette di cifrare una stringa qualsiasi in modo statico, con una chiave privata DES generata da una stringa decisa da noi (può essere utile per creare un file binario di configurazione, o altro):
public class CryptoWithDES{
private Cipher ecipher;
private Cipher dcipher;
private static int ITERATION = 19;
// 8-byte Salt
private static byte[] SALT = {
(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
(byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
};
/**
* Create a DES Security Manager with DES (for decrypt and encrypt)
* key depending from a passPhrase
* @param passPhrase to generate the DES key
*/
public CryptoWithDES(String passPhrase){
// Create the key
KeySpec keySpec =
new PBEKeySpec(passPhrase.toCharArray(), SALT, ITERATION);
SecretKey key;
try {
key = SecretKeyFactory.
getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec =
new PBEParameterSpec(SALT, ITERATION);
// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (InvalidKeySpecException e) {
} catch (NoSuchAlgorithmException e) {
} catch (NoSuchPaddingException e) {
} catch (InvalidKeyException e) {
} catch (InvalidAlgorithmParameterException e) {
}
}
/**
* Decrypt a message with the DES key and convert to String
* @param en_message the encrypted message to decrypt
* @return the message decrypted
*/
public String decrypt(byte[] en_message) {
return Helper.getStringFromByte(this.decrypt(en_message));
}
/**
* Encrypt a String with the DES key
* @param message the message to encrypt
* @return the message encrypted
*/
public byte[] encrypt(String message) {
// Encode the string into bytes
byte[] msg = Helper.getByteFromString(message);
byte[] enc = null;
try {
// Encrypt
enc = ecipher.doFinal(msg);
return enc;
} catch (IllegalBlockSizeException e) {
} catch (BadPaddingException e) {
}
return null;
}
public static void main(String[] args){
CryptoWithDES c = new CryptoWithDES("Chiave privata");
System.out.println(c.decrypt(c.encrypt("Stringa segreta")));
}
}
La fonte la potete trovare qui.






