package test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Date;
import javax.crypto.Cipher;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.util.io.pem.PemReader;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import sun.misc.BASE64Encoder;
public class GenerateRSAKeys {
static String path = "C:/Users/muia/workspace web/progetti/jling/jling/src/main/resources/META-INF/";
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
String publicKeyFilename = null;
String privateKeyFilename = null;
GenerateRSAKeys generateRSAKeys = new GenerateRSAKeys();
// if (args.length < 2) {
// System.err.println("Usage: java "
// + generateRSAKeys.getClass().getName()
// + " Public_Key_Filename Private_Key_Filename");
// System.exit(1);
// }
// publicKeyFilename = path+"client_pub.key";
// privateKeyFilename = path+"client_priv.key";
// generateRSAKeys.generate(publicKeyFilename, privateKeyFilename);
// generateSelfSignedX509Certificate();
PublicKey publicKey = loadPublicKey();
// byte[] encrypted = encrypt("Sei uno Stronzo".getBytes("UTF-8"),
// publicKey);
// System.out.println(Arrays.toString(encrypted));
PrivateKey privateKey = loadPrivateKey(GenerateRSAKeys.class
.getResourceAsStream("/META-INF/priv-johndoe.pem"));
// byte[] message = decrypt(encrypted, privateKey);
// System.out.println("MESSAGE = " + new String(message, "UTF-8"));
// GenerateRSAKeys.encryptDecryptFile(path + "data_enc.txt", path
// + "data.txt", privateKey, Cipher.DECRYPT_MODE);
}
public static byte[] decrypt(byte[] text, PrivateKey key) throws Exception {
byte[] dectyptedText = null;
// decrypt the text using the private key
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(text);
return dectyptedText;
}
public static byte[] encrypt(byte[] text, PublicKey key) throws Exception {
byte[] cipherText = null;
// get an RSA cipher object and print the provider
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
System.out.println("nProvider is: " + cipher.getProvider().getInfo());
// encrypt the plaintext using the public key
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text);
return cipherText;
}
static PublicKey loadPublicKey() throws Exception {
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
final PemReader reader = new PemReader(new InputStreamReader(
GenerateRSAKeys.class
.getResourceAsStream("/META-INF/public-johndoe.pem")));
final byte[] pubKey = reader.readPemObject().getContent();
final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKey);
reader.close();
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
return publicKey;
}
static PrivateKey loadPrivateKey(InputStream in) throws Exception {
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
final PemReader reader = new PemReader(new InputStreamReader(in));
final byte[] pubKey = reader.readPemObject().getContent();
// final X509EncodedKeySpec publicKeySpec = new
// X509EncodedKeySpec(pubKey);
reader.close();
PKCS8EncodedKeySpec publicKeySpec = new PKCS8EncodedKeySpec(pubKey);
PrivateKey publicKey = keyFactory.generatePrivate(publicKeySpec);
return publicKey;
}
static void generateSelfSignedX509Certificate() throws Exception {
// yesterday
Date validityBeginDate = new Date(System.currentTimeMillis() - 24 * 60
* 60 * 1000);
// in 2 years
Date validityEndDate = new Date(System.currentTimeMillis() + 2 * 365
* 24 * 60 * 60 * 1000);
// GENERATE THE PUBLIC/PRIVATE RSA KEY PAIR
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA",
"BC");
keyPairGenerator.initialize(1024, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// GENERATE THE X509 CERTIFICATE
// V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
X500Principal dnName = new X500Principal("CN=John Doe");
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setSubjectDN(dnName);
certGen.setIssuerDN(dnName); // use the same
certGen.setNotBefore(validityBeginDate);
certGen.setNotAfter(validityEndDate);
certGen.setPublicKey(keyPair.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC");
// DUMP CERTIFICATE AND KEY PAIR
// System.out.println(Strings.repeat("=", 80));
System.out.println("CERTIFICATE TO_STRING");
// System.out.println(Strings.repeat("=", 80));
System.out.println();
System.out.println(cert);
System.out.println();
System.out.println("WRITE CERTIFICATE");
export(cert, new File(path, "cert-johndoe.cert"), true);
// System.out.println(Strings.repeat("=", 80));
System.out
.println("CERTIFICATE PEM (to store in a cert-johndoe.pem file)");
// System.out.println(Strings.repeat("=", 80));
System.out.println();
PEMWriter pemWriter = new PEMWriter(new PrintWriter(new File(path,
"cert-johndoe.pem")));
pemWriter.writeObject(cert);
pemWriter.flush();
System.out.println();
pemWriter.close();
// System.out.println(Strings.repeat("=", 80));
System.out
.println("PRIVATE KEY PEM (to store in a priv-johndoe.pem file)");
// System.out.println(Strings.repeat("=", 80));
System.out.println();
pemWriter = new PEMWriter(new PrintWriter(new File(path,
"priv-johndoe.pem")));
pemWriter.writeObject(keyPair.getPrivate());
pemWriter.flush();
System.out.println();
pemWriter.close();
// System.out.println(Strings.repeat("=", 80));
System.out
.println("Public KEY PEM (to store in a priv-johndoe.pem file)");
// System.out.println(Strings.repeat("=", 80));
System.out.println();
pemWriter = new PEMWriter(new PrintWriter(new File(path,
"public-johndoe.pem")));
pemWriter.writeObject(keyPair.getPublic());
pemWriter.flush();
pemWriter.close();
System.out.println();
}
public static void export(java.security.cert.Certificate cert, File file,
boolean binary) {
try {
// Get the encoded form which is suitable for exporting
byte[] buf = cert.getEncoded();
FileOutputStream os = new FileOutputStream(file);
if (binary) {
// Write in binary form
os.write(buf);
} else {
// Write in text form
Writer wr = new OutputStreamWriter(os, Charset.forName("UTF-8"));
wr.write("-----BEGIN CERTIFICATE-----\n");
wr.write(new sun.misc.BASE64Encoder().encode(buf));
wr.write("\n-----END CERTIFICATE-----\n");
wr.flush();
}
os.close();
} catch (CertificateEncodingException e) {
} catch (IOException e) {
}
}
private void generate(String publicKeyFilename, String privateFilename) {
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
// Create the public and private keys
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA",
"BC");
BASE64Encoder b64 = new BASE64Encoder();
SecureRandom random = new SecureRandom();
generator.initialize(1024, random);
KeyPair pair = generator.generateKeyPair();
Key pubKey = pair.getPublic();
Key privKey = pair.getPrivate();
System.out
.println("publicKey : " + b64.encode(pubKey.getEncoded()));
System.out.println("privateKey : "
+ b64.encode(privKey.getEncoded()));
BufferedWriter out = new BufferedWriter(new FileWriter(
publicKeyFilename));
out.write(b64.encode(pubKey.getEncoded()));
out.close();
out = new BufferedWriter(new FileWriter(privateFilename));
out.write(b64.encode(privKey.getEncoded()));
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
public static void encryptDecryptFile(String srcFileName,
String destFileName, Key key, int cipherMode) throws Exception {
OutputStream outputWriter = null;
InputStream inputReader = null;
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
String textLine = null;
byte[] buf = cipherMode == Cipher.ENCRYPT_MODE ? new byte[100]
: new byte[128];
int bufl;
// init the Cipher object for Encryption�
cipher.init(cipherMode, key);
// start FileIO
outputWriter = new FileOutputStream(destFileName);
inputReader = new FileInputStream(srcFileName);
while ((bufl = inputReader.read(buf)) != -1) {
byte[] encText = null;
if (cipherMode == Cipher.ENCRYPT_MODE) {
encText = encrypt(copyBytes(buf, bufl), (PublicKey) key);
} else {
encText = decrypt(copyBytes(buf, bufl), (PrivateKey) key);
}
outputWriter.write(encText);
}
outputWriter.flush();
} finally {
try {
if (outputWriter != null) {
outputWriter.close();
}
if (inputReader != null) {
inputReader.close();
}
} catch (Exception e) {
// do nothing�
}
}
}
public static byte[] copyBytes(byte[] arr, int length) {
byte[] newArr = null;
if (arr.length == length) {
newArr = arr;
} else {
newArr = new byte[length];
for (int i = 0; i < length; i++) {
newArr[i] = (byte) arr[i];
}
}
return newArr;
}
}