Files
gateway-mnp-dbc/dbcmnpsrc/FE/mnpdev/build/protection/sistemi/client/KeyGen.java
2024-05-13 12:54:14 +02:00

89 lines
3.0 KiB
Java

package client;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
import java.text.SimpleDateFormat;
/**
* User: germano.giudici
* Date: 3-apr-2009
*/
public class KeyGen {
static final String TRIPLE_DES_CHIPER = "DESede/ECB/PKCS5Padding";
static final String TRIPLE_DES_KEY = "DESede";
static String passphrase = "generate a key of course";
static Key chiave3DES;
public static void main(String[] args) throws Exception {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
simpleDateFormat.parse(args[0]);
createKey();
} catch (Exception e) {
System.out.println("Uso: Inserire una data nella forma yyyy.MM.dd");
System.exit(0);
}
// Encrypt
String encrypted = cripta3DES(args[0]);
System.out.println("activationkey = " + encrypted);
// Decrypt
String decrypted = decripta3DES(encrypted);
System.out.println("data di scadenza = " + decrypted);
System.out.println("\n\ncopiare la activationkey nella sezione ATTIVAZIONE del file simulatore.properties");
}
public static String cripta3DES(String value) throws Exception{
byte[] res = null;
Cipher cipher = Cipher.getInstance(TRIPLE_DES_CHIPER);
cipher.init(Cipher.ENCRYPT_MODE, chiave3DES);
byte[] val = value.getBytes();
res = new byte[cipher.getOutputSize(val.length)];
int size = cipher.update(val, 0, val.length, res, 0);
size += cipher.doFinal(res,size);
return toString(res,res.length);
}
public static String decripta3DES(String value) throws Exception{
Cipher cipher = Cipher.getInstance(TRIPLE_DES_CHIPER);
cipher.init(Cipher.DECRYPT_MODE, chiave3DES);
return new String(cipher.doFinal(toByteArray(value)));
}
private static void createKey() throws Exception{
DESedeKeySpec spec = null;
spec = new DESedeKeySpec(passphrase.getBytes());
chiave3DES = SecretKeyFactory.getInstance(TRIPLE_DES_KEY).generateSecret(spec);
}
private static final byte[] toByteArray(String string) throws Exception{
BASE64Decoder decoder = new BASE64Decoder();
byte[] raw = decoder.decodeBuffer(string);
return raw;
}
private static final String toString(byte[] bytes,int length) {
BASE64Encoder encoder = new BASE64Encoder();
String base64 = encoder.encode(bytes);
return base64;
}
}