Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package chapter4;
- import java.io.ByteArrayOutputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.math.BigInteger;
- import java.security.GeneralSecurityException;
- import java.security.InvalidAlgorithmParameterException;
- import java.security.InvalidKeyException;
- import java.security.KeyPair;
- import java.security.KeyPairGenerator;
- import java.security.NoSuchAlgorithmException;
- import java.security.PrivateKey;
- import java.security.PublicKey;
- import java.security.SecureRandom;
- import java.security.Signature;
- import java.security.cert.X509Certificate;
- import java.security.spec.InvalidKeySpecException;
- import java.util.Date;
- import javax.crypto.BadPaddingException;
- import javax.crypto.Cipher;
- import javax.crypto.IllegalBlockSizeException;
- import javax.crypto.NoSuchPaddingException;
- import javax.crypto.SecretKey;
- import javax.crypto.SecretKeyFactory;
- import javax.crypto.spec.PBEKeySpec;
- import javax.crypto.spec.PBEParameterSpec;
- import sun.security.x509.AlgorithmId;
- import sun.security.x509.CertificateAlgorithmId;
- import sun.security.x509.CertificateIssuerName;
- import sun.security.x509.CertificateSerialNumber;
- import sun.security.x509.CertificateSubjectName;
- import sun.security.x509.CertificateValidity;
- import sun.security.x509.CertificateVersion;
- import sun.security.x509.CertificateX509Key;
- import sun.security.x509.X500Name;
- import sun.security.x509.X509CertImpl;
- import sun.security.x509.X509CertInfo;
- class GenSig {
- public static void main(String[] args) {
- GenSig gensig = new GenSig();
- KeyPair keyPair = gensig.generateKeyPair();
- try {
- X509Certificate certificate = gensig.generateCertificate(
- "CN=Test, L=London, C=GB", keyPair, 3, "SHA1withRSA");
- FileOutputStream pvt = new FileOutputStream("d:\\newpass.cer");
- try {
- pvt.write(certificate.getEncoded());
- pvt.flush();
- } finally {
- pvt.close();
- }
- } catch (GeneralSecurityException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- for (Object obj : java.security.Security.getAlgorithms("Cipher")) {
- System.out.println(obj);
- }
- }
- KeyPair generateKeyPair() {
- KeyPair pair = null;
- /* Generate a DSA signature */
- /*
- * if (args.length != 1) {
- * System.out.println("Usage: GenSig nameOfFileToSign"); } else
- */try {
- /* Generate a key pair */
- String password = "1234";
- KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
- SecureRandom random = Utils.createFixedRandom();// SecureRandom.getInstance("SHA1PRNG",
- // "SUN");
- keyGen.initialize(1024, random);
- pair = keyGen.generateKeyPair();
- PrivateKey privkey1 = pair.getPrivate();
- PublicKey pubKey1 = pair.getPublic();
- byte[] privateKeyBytes = pair.getPrivate().getEncoded();
- byte[] encryptedPrivateKeyBytes = passwordEncrypt(
- password.toCharArray(), privateKeyBytes);
- createPrivateKeyFile(pair);
- createPublicKeyFile(pair);
- /* Create a Signature object and initialize it with the private key */
- Signature dsa = Signature.getInstance("SHA1withRSA");
- dsa.initSign(privkey1);
- /* Update and sign the data */
- /*
- * FileInputStream fis = new FileInputStream(args[0]);
- * BufferedInputStream bufin = new BufferedInputStream(fis); byte[]
- * buffer = new byte[1024]; int len; while (bufin.available() != 0)
- * { len = bufin.read(buffer); dsa.update(buffer, 0, len); };
- *
- * bufin.close();
- */
- /*
- * Now that all the data to be signed has been read in, generate a
- * signature for it
- */
- byte[] realSig = dsa.sign();
- /* Save the signature in a file */// Rimasig
- FileOutputStream sigfos = new FileOutputStream("D:\\Rimasig1");
- sigfos.write(realSig);
- sigfos.close();
- /* Save the public key in a file */// Rimasuepk
- byte[] key = pubKey1.getEncoded();
- FileOutputStream keyfos = new FileOutputStream("D:\\RimaPub.der");
- keyfos.write(key);
- keyfos.close();
- Cipher cipher = Cipher
- .getInstance("RSA"/* "RSA/NONE/NoPadding" *//* , "BC" */);
- cipher.init(Cipher.ENCRYPT_MODE, pubKey1, random);
- byte[] input = new byte[] { (byte) 0xbe, (byte) 0xef };
- System.out.println("input : " + Utils.toHex(input));
- byte[] cipherText = cipher.doFinal(input);
- System.out.println("cipher: " + Utils.toHex(cipherText));
- // decryption step
- cipher.init(Cipher.DECRYPT_MODE, privkey1);
- byte[] plainText = cipher.doFinal(cipherText);
- System.out.println("plain : " + Utils.toHex(plainText));
- } catch (Exception e) {
- System.err.println("Caught exception " + e.toString());
- }
- return pair;
- }
- private void createPrivateKeyFile(KeyPair pair) {
- try {
- FileOutputStream pvt = new FileOutputStream("d:\\pvtkey.der");
- try {
- pvt.write(pair.getPrivate().getEncoded());
- pvt.flush();
- } finally {
- pvt.close();
- }
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- private void createPublicKeyFile(KeyPair pair) {
- try {
- FileOutputStream pvt = new FileOutputStream("d:\\pubkey.der");
- try {
- pvt.write(pair.getPublic().getEncoded());
- pvt.flush();
- } finally {
- pvt.close();
- }
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- X509Certificate generateCertificate(String dn, KeyPair pair, int days,
- String algorithm) throws GeneralSecurityException, IOException {
- PrivateKey privkey = pair.getPrivate();
- X509CertInfo info = new X509CertInfo();
- Date from = new Date();
- Date to = new Date(from.getTime() + days * 86400000l);
- CertificateValidity interval = new CertificateValidity(from, to);
- BigInteger sn = new BigInteger(64, new SecureRandom());
- X500Name owner = new X500Name(dn);
- info.set(X509CertInfo.VALIDITY, interval);
- info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
- info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
- info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
- info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
- info.set(X509CertInfo.VERSION, new CertificateVersion(
- CertificateVersion.V3));
- AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
- info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
- // Sign the cert to identify the algorithm that's used.
- X509CertImpl cert = new X509CertImpl(info);
- cert.sign(privkey, algorithm);
- // Update the algorith, and resign.
- algo = (AlgorithmId) cert.get(X509CertImpl.SIG_ALG);
- info.set(CertificateAlgorithmId.NAME + "."
- + CertificateAlgorithmId.ALGORITHM, algo);
- cert = new X509CertImpl(info);
- cert.sign(privkey, algorithm);
- return cert;
- }
- 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
- * X509V1CertificateGenerator
- * certGen =
- * new
- * X509V1CertificateGenerator
- * ();
- * 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(
- * 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
- * (
- * System.out
- * ));
- * pemWriter
- * .
- * writeObject
- * (cert);
- * pemWriter
- * .flush();
- * System
- * .out
- * .println
- * ();
- *
- * 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
- * .
- * writeObject
- * (keyPair.
- * getPrivate
- * ());
- * pemWriter
- * .flush();
- * System
- * .out
- * .println
- * ();
- */
- }
- private static byte[] passwordEncrypt(char[] password, byte[] plaintext) /*
- * throws
- * Exception
- */{
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- try {
- int MD5_ITERATIONS = 1000;
- byte[] salt = new byte[8];
- SecureRandom random = new SecureRandom();
- random.nextBytes(salt);
- PBEKeySpec keySpec = new PBEKeySpec(password);
- SecretKeyFactory keyFactory = SecretKeyFactory
- .getInstance("PBEWITHMD5ANDTRIPLEDES"/* "PBEWithSHAAndTwofish-CBC" */);
- SecretKey key = keyFactory.generateSecret(keySpec);
- PBEParameterSpec paramSpec = new PBEParameterSpec(salt,
- MD5_ITERATIONS);
- Cipher cipher = Cipher.getInstance("PBEWITHMD5ANDTRIPLEDES");
- cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
- byte[] ciphertext = cipher.doFinal(plaintext);
- baos.write(salt);
- baos.write(ciphertext);
- return baos.toByteArray();
- } catch (InvalidKeyException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (NoSuchAlgorithmException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InvalidKeySpecException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (NoSuchPaddingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InvalidAlgorithmParameterException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalBlockSizeException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (BadPaddingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return baos.toByteArray();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement