Advertisement
Guest User

Untitled

a guest
Oct 8th, 2013
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.59 KB | None | 0 0
  1. package chapter4;
  2.  
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.math.BigInteger;
  8. import java.security.GeneralSecurityException;
  9. import java.security.InvalidAlgorithmParameterException;
  10. import java.security.InvalidKeyException;
  11. import java.security.KeyPair;
  12. import java.security.KeyPairGenerator;
  13. import java.security.NoSuchAlgorithmException;
  14. import java.security.PrivateKey;
  15. import java.security.PublicKey;
  16. import java.security.SecureRandom;
  17. import java.security.Signature;
  18. import java.security.cert.X509Certificate;
  19. import java.security.spec.InvalidKeySpecException;
  20. import java.util.Date;
  21.  
  22. import javax.crypto.BadPaddingException;
  23. import javax.crypto.Cipher;
  24. import javax.crypto.IllegalBlockSizeException;
  25. import javax.crypto.NoSuchPaddingException;
  26. import javax.crypto.SecretKey;
  27. import javax.crypto.SecretKeyFactory;
  28. import javax.crypto.spec.PBEKeySpec;
  29. import javax.crypto.spec.PBEParameterSpec;
  30.  
  31. import sun.security.x509.AlgorithmId;
  32. import sun.security.x509.CertificateAlgorithmId;
  33. import sun.security.x509.CertificateIssuerName;
  34. import sun.security.x509.CertificateSerialNumber;
  35. import sun.security.x509.CertificateSubjectName;
  36. import sun.security.x509.CertificateValidity;
  37. import sun.security.x509.CertificateVersion;
  38. import sun.security.x509.CertificateX509Key;
  39. import sun.security.x509.X500Name;
  40. import sun.security.x509.X509CertImpl;
  41. import sun.security.x509.X509CertInfo;
  42.  
  43. class GenSig {
  44.  
  45.     public static void main(String[] args) {
  46.         GenSig gensig = new GenSig();
  47.         KeyPair keyPair = gensig.generateKeyPair();
  48.         try {
  49.             X509Certificate certificate = gensig.generateCertificate(
  50.                     "CN=Test, L=London, C=GB", keyPair, 3, "SHA1withRSA");
  51.             FileOutputStream pvt = new FileOutputStream("d:\\newpass.cer");
  52.             try {
  53.                 pvt.write(certificate.getEncoded());
  54.                 pvt.flush();
  55.             } finally {
  56.                 pvt.close();
  57.             }
  58.  
  59.         } catch (GeneralSecurityException e) {
  60.             // TODO Auto-generated catch block
  61.             e.printStackTrace();
  62.         } catch (IOException e) {
  63.             // TODO Auto-generated catch block
  64.             e.printStackTrace();
  65.         }
  66.  
  67.         for (Object obj : java.security.Security.getAlgorithms("Cipher")) {
  68.             System.out.println(obj);
  69.         }
  70.     }
  71.  
  72.     KeyPair generateKeyPair() {
  73.  
  74.         KeyPair pair = null;
  75.         /* Generate a DSA signature */
  76.         /*
  77.          * if (args.length != 1) {
  78.          * System.out.println("Usage: GenSig nameOfFileToSign"); } else
  79.          */try {
  80.  
  81.             /* Generate a key pair */
  82.             String password = "1234";
  83.             KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  84.             SecureRandom random = Utils.createFixedRandom();// SecureRandom.getInstance("SHA1PRNG",
  85.                                                             // "SUN");
  86.             keyGen.initialize(1024, random);
  87.             pair = keyGen.generateKeyPair();
  88.             PrivateKey privkey1 = pair.getPrivate();
  89.             PublicKey pubKey1 = pair.getPublic();
  90.  
  91.             byte[] privateKeyBytes = pair.getPrivate().getEncoded();
  92.             byte[] encryptedPrivateKeyBytes = passwordEncrypt(
  93.                     password.toCharArray(), privateKeyBytes);
  94.             createPrivateKeyFile(pair);
  95.             createPublicKeyFile(pair);
  96.  
  97.             /* Create a Signature object and initialize it with the private key */
  98.             Signature dsa = Signature.getInstance("SHA1withRSA");
  99.             dsa.initSign(privkey1);
  100.  
  101.             /* Update and sign the data */
  102.  
  103.             /*
  104.              * FileInputStream fis = new FileInputStream(args[0]);
  105.              * BufferedInputStream bufin = new BufferedInputStream(fis); byte[]
  106.              * buffer = new byte[1024]; int len; while (bufin.available() != 0)
  107.              * { len = bufin.read(buffer); dsa.update(buffer, 0, len); };
  108.              *
  109.              * bufin.close();
  110.              */
  111.             /*
  112.              * Now that all the data to be signed has been read in, generate a
  113.              * signature for it
  114.              */
  115.  
  116.             byte[] realSig = dsa.sign();
  117.  
  118.             /* Save the signature in a file */// Rimasig
  119.             FileOutputStream sigfos = new FileOutputStream("D:\\Rimasig1");
  120.             sigfos.write(realSig);
  121.             sigfos.close();
  122.  
  123.             /* Save the public key in a file */// Rimasuepk
  124.             byte[] key = pubKey1.getEncoded();
  125.             FileOutputStream keyfos = new FileOutputStream("D:\\RimaPub.der");
  126.             keyfos.write(key);
  127.             keyfos.close();
  128.  
  129.             Cipher cipher = Cipher
  130.                     .getInstance("RSA"/* "RSA/NONE/NoPadding" *//* , "BC" */);
  131.             cipher.init(Cipher.ENCRYPT_MODE, pubKey1, random);
  132.             byte[] input = new byte[] { (byte) 0xbe, (byte) 0xef };
  133.             System.out.println("input : " + Utils.toHex(input));
  134.             byte[] cipherText = cipher.doFinal(input);
  135.             System.out.println("cipher: " + Utils.toHex(cipherText));
  136.  
  137.             // decryption step
  138.  
  139.             cipher.init(Cipher.DECRYPT_MODE, privkey1);
  140.             byte[] plainText = cipher.doFinal(cipherText);
  141.             System.out.println("plain : " + Utils.toHex(plainText));
  142.  
  143.         } catch (Exception e) {
  144.             System.err.println("Caught exception " + e.toString());
  145.         }
  146.  
  147.         return pair;
  148.  
  149.     }
  150.  
  151.     private void createPrivateKeyFile(KeyPair pair) {
  152.         try {
  153.             FileOutputStream pvt = new FileOutputStream("d:\\pvtkey.der");
  154.             try {
  155.                 pvt.write(pair.getPrivate().getEncoded());
  156.                 pvt.flush();
  157.             } finally {
  158.                 pvt.close();
  159.             }
  160.         } catch (FileNotFoundException e) {
  161.             // TODO Auto-generated catch block
  162.             e.printStackTrace();
  163.         } catch (IOException e) {
  164.             // TODO Auto-generated catch block
  165.             e.printStackTrace();
  166.         }
  167.     }
  168.  
  169.     private void createPublicKeyFile(KeyPair pair) {
  170.         try {
  171.             FileOutputStream pvt = new FileOutputStream("d:\\pubkey.der");
  172.             try {
  173.                 pvt.write(pair.getPublic().getEncoded());
  174.                 pvt.flush();
  175.             } finally {
  176.                 pvt.close();
  177.             }
  178.         } catch (FileNotFoundException e) {
  179.             // TODO Auto-generated catch block
  180.             e.printStackTrace();
  181.         } catch (IOException e) {
  182.             // TODO Auto-generated catch block
  183.             e.printStackTrace();
  184.         }
  185.     }
  186.  
  187.     X509Certificate generateCertificate(String dn, KeyPair pair, int days,
  188.             String algorithm) throws GeneralSecurityException, IOException {
  189.         PrivateKey privkey = pair.getPrivate();
  190.         X509CertInfo info = new X509CertInfo();
  191.  
  192.         Date from = new Date();
  193.         Date to = new Date(from.getTime() + days * 86400000l);
  194.         CertificateValidity interval = new CertificateValidity(from, to);
  195.         BigInteger sn = new BigInteger(64, new SecureRandom());
  196.         X500Name owner = new X500Name(dn);
  197.  
  198.         info.set(X509CertInfo.VALIDITY, interval);
  199.         info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
  200.         info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
  201.         info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
  202.         info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
  203.         info.set(X509CertInfo.VERSION, new CertificateVersion(
  204.                 CertificateVersion.V3));
  205.         AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
  206.         info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
  207.  
  208.         // Sign the cert to identify the algorithm that's used.
  209.         X509CertImpl cert = new X509CertImpl(info);
  210.         cert.sign(privkey, algorithm);
  211.  
  212.         // Update the algorith, and resign.
  213.         algo = (AlgorithmId) cert.get(X509CertImpl.SIG_ALG);
  214.         info.set(CertificateAlgorithmId.NAME + "."
  215.                 + CertificateAlgorithmId.ALGORITHM, algo);
  216.         cert = new X509CertImpl(info);
  217.         cert.sign(privkey, algorithm);
  218.         return cert;
  219.     }
  220.  
  221.     static void generateSelfSignedX509Certificate() throws Exception {/*
  222.                                                                      *
  223.                                                                      * //
  224.                                                                      * yesterday
  225.                                                                      * Date
  226.                                                                      * validityBeginDate
  227.                                                                      * = new
  228.                                                                      * Date
  229.                                                                      * (System.
  230.                                                                      * currentTimeMillis
  231.                                                                      * () - 24 *
  232.                                                                      * 60 * 60 *
  233.                                                                      * 1000); //
  234.                                                                      * in 2
  235.                                                                      * years
  236.                                                                      * Date
  237.                                                                      * validityEndDate
  238.                                                                      * = new
  239.                                                                      * Date
  240.                                                                      * (System.
  241.                                                                      * currentTimeMillis
  242.                                                                      * () + 2 *
  243.                                                                      * 365 * 24
  244.                                                                      * * 60 * 60
  245.                                                                      * * 1000);
  246.                                                                      *
  247.                                                                      * //
  248.                                                                      * GENERATE
  249.                                                                      * THE
  250.                                                                      * PUBLIC
  251.                                                                      * /PRIVATE
  252.                                                                      * RSA KEY
  253.                                                                      * PAIR
  254.                                                                      * KeyPairGenerator
  255.                                                                      * keyPairGenerator
  256.                                                                      * =
  257.                                                                      * KeyPairGenerator
  258.                                                                      * .
  259.                                                                      * getInstance
  260.                                                                      * ("RSA",
  261.                                                                      * "BC");
  262.                                                                      * keyPairGenerator
  263.                                                                      * .
  264.                                                                      * initialize
  265.                                                                      * (1024,
  266.                                                                      * new
  267.                                                                      * SecureRandom
  268.                                                                      * ());
  269.                                                                      *
  270.                                                                      * KeyPair
  271.                                                                      * keyPair =
  272.                                                                      * keyPairGenerator
  273.                                                                      * .
  274.                                                                      * generateKeyPair
  275.                                                                      * ();
  276.                                                                      *
  277.                                                                      * //
  278.                                                                      * GENERATE
  279.                                                                      * THE X509
  280.                                                                      * CERTIFICATE
  281.                                                                      * X509V1CertificateGenerator
  282.                                                                      * certGen =
  283.                                                                      * new
  284.                                                                      * X509V1CertificateGenerator
  285.                                                                      * ();
  286.                                                                      * X500Principal
  287.                                                                      * dnName =
  288.                                                                      * new
  289.                                                                      * X500Principal
  290.                                                                      * (
  291.                                                                      * "CN=John Doe"
  292.                                                                      * );
  293.                                                                      *
  294.                                                                      * certGen.
  295.                                                                      * setSerialNumber
  296.                                                                      * (
  297.                                                                      * BigInteger
  298.                                                                      * .valueOf(
  299.                                                                      * System.
  300.                                                                      * currentTimeMillis
  301.                                                                      * ()));
  302.                                                                      * certGen
  303.                                                                      * .setSubjectDN
  304.                                                                      * (dnName);
  305.                                                                      * certGen
  306.                                                                      * .setIssuerDN
  307.                                                                      * (dnName);
  308.                                                                      * // use
  309.                                                                      * the same
  310.                                                                      * certGen
  311.                                                                      * .setNotBefore
  312.                                                                      * (
  313.                                                                      * validityBeginDate
  314.                                                                      * );
  315.                                                                      * certGen
  316.                                                                      * .setNotAfter
  317.                                                                      * (
  318.                                                                      * validityEndDate
  319.                                                                      * );
  320.                                                                      * certGen
  321.                                                                      * .setPublicKey
  322.                                                                      * (keyPair.
  323.                                                                      * getPublic
  324.                                                                      * ());
  325.                                                                      * certGen.
  326.                                                                      * setSignatureAlgorithm
  327.                                                                      * (
  328.                                                                      * "SHA256WithRSAEncryption"
  329.                                                                      * );
  330.                                                                      *
  331.                                                                      * X509Certificate
  332.                                                                      * cert =
  333.                                                                      * certGen
  334.                                                                      * .generate
  335.                                                                      * (keyPair.
  336.                                                                      * getPrivate
  337.                                                                      * (),
  338.                                                                      * "BC");
  339.                                                                      *
  340.                                                                      * // DUMP
  341.                                                                      * CERTIFICATE
  342.                                                                      * AND KEY
  343.                                                                      * PAIR
  344.                                                                      *
  345.                                                                      * System.out
  346.                                                                      * .println(
  347.                                                                      * Strings
  348.                                                                      * .repeat
  349.                                                                      * ("=",
  350.                                                                      * 80));
  351.                                                                      * System
  352.                                                                      * .out
  353.                                                                      * .println(
  354.                                                                      * "CERTIFICATE TO_STRING"
  355.                                                                      * );
  356.                                                                      * System.
  357.                                                                      * out
  358.                                                                      * .println
  359.                                                                      * (Strings
  360.                                                                      * .repeat
  361.                                                                      * ("=",
  362.                                                                      * 80));
  363.                                                                      * System
  364.                                                                      * .out
  365.                                                                      * .println
  366.                                                                      * ();
  367.                                                                      * System
  368.                                                                      * .out
  369.                                                                      * .println
  370.                                                                      * (cert);
  371.                                                                      * System
  372.                                                                      * .out
  373.                                                                      * .println
  374.                                                                      * ();
  375.                                                                      *
  376.                                                                      * System.out
  377.                                                                      * .println(
  378.                                                                      * Strings
  379.                                                                      * .repeat
  380.                                                                      * ("=",
  381.                                                                      * 80));
  382.                                                                      * System
  383.                                                                      * .out
  384.                                                                      * .println(
  385.                                                                      * "CERTIFICATE PEM (to store in a cert-johndoe.pem file)"
  386.                                                                      * );
  387.                                                                      * System.
  388.                                                                      * out
  389.                                                                      * .println
  390.                                                                      * (Strings
  391.                                                                      * .repeat
  392.                                                                      * ("=",
  393.                                                                      * 80));
  394.                                                                      * System
  395.                                                                      * .out
  396.                                                                      * .println
  397.                                                                      * ();
  398.                                                                      * PEMWriter
  399.                                                                      * pemWriter
  400.                                                                      * = new
  401.                                                                      * PEMWriter
  402.                                                                      * (new
  403.                                                                      * PrintWriter
  404.                                                                      * (
  405.                                                                      * System.out
  406.                                                                      * ));
  407.                                                                      * pemWriter
  408.                                                                      * .
  409.                                                                      * writeObject
  410.                                                                      * (cert);
  411.                                                                      * pemWriter
  412.                                                                      * .flush();
  413.                                                                      * System
  414.                                                                      * .out
  415.                                                                      * .println
  416.                                                                      * ();
  417.                                                                      *
  418.                                                                      * System.out
  419.                                                                      * .println(
  420.                                                                      * Strings
  421.                                                                      * .repeat
  422.                                                                      * ("=",
  423.                                                                      * 80));
  424.                                                                      * System
  425.                                                                      * .out
  426.                                                                      * .println(
  427.                                                                      * "PRIVATE KEY PEM (to store in a priv-johndoe.pem file)"
  428.                                                                      * );
  429.                                                                      * System.
  430.                                                                      * out
  431.                                                                      * .println
  432.                                                                      * (Strings
  433.                                                                      * .repeat
  434.                                                                      * ("=",
  435.                                                                      * 80));
  436.                                                                      * System
  437.                                                                      * .out
  438.                                                                      * .println
  439.                                                                      * ();
  440.                                                                      * pemWriter
  441.                                                                      * .
  442.                                                                      * writeObject
  443.                                                                      * (keyPair.
  444.                                                                      * getPrivate
  445.                                                                      * ());
  446.                                                                      * pemWriter
  447.                                                                      * .flush();
  448.                                                                      * System
  449.                                                                      * .out
  450.                                                                      * .println
  451.                                                                      * ();
  452.                                                                      */
  453.     }
  454.  
  455.     private static byte[] passwordEncrypt(char[] password, byte[] plaintext) /*
  456.                                                                              * throws
  457.                                                                              * Exception
  458.                                                                              */{
  459.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  460.         try {
  461.             int MD5_ITERATIONS = 1000;
  462.             byte[] salt = new byte[8];
  463.             SecureRandom random = new SecureRandom();
  464.             random.nextBytes(salt);
  465.  
  466.             PBEKeySpec keySpec = new PBEKeySpec(password);
  467.             SecretKeyFactory keyFactory = SecretKeyFactory
  468.                     .getInstance("PBEWITHMD5ANDTRIPLEDES"/* "PBEWithSHAAndTwofish-CBC" */);
  469.             SecretKey key = keyFactory.generateSecret(keySpec);
  470.             PBEParameterSpec paramSpec = new PBEParameterSpec(salt,
  471.                     MD5_ITERATIONS);
  472.             Cipher cipher = Cipher.getInstance("PBEWITHMD5ANDTRIPLEDES");
  473.             cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
  474.  
  475.             byte[] ciphertext = cipher.doFinal(plaintext);
  476.  
  477.             baos.write(salt);
  478.             baos.write(ciphertext);
  479.             return baos.toByteArray();
  480.         } catch (InvalidKeyException e) {
  481.             // TODO Auto-generated catch block
  482.             e.printStackTrace();
  483.         } catch (NoSuchAlgorithmException e) {
  484.             // TODO Auto-generated catch block
  485.             e.printStackTrace();
  486.         } catch (InvalidKeySpecException e) {
  487.             // TODO Auto-generated catch block
  488.             e.printStackTrace();
  489.         } catch (NoSuchPaddingException e) {
  490.             // TODO Auto-generated catch block
  491.             e.printStackTrace();
  492.         } catch (InvalidAlgorithmParameterException e) {
  493.             // TODO Auto-generated catch block
  494.             e.printStackTrace();
  495.         } catch (IllegalBlockSizeException e) {
  496.             // TODO Auto-generated catch block
  497.             e.printStackTrace();
  498.         } catch (BadPaddingException e) {
  499.             // TODO Auto-generated catch block
  500.             e.printStackTrace();
  501.         } catch (IOException e) {
  502.             // TODO Auto-generated catch block
  503.             e.printStackTrace();
  504.         }
  505.         return baos.toByteArray();
  506.  
  507.     }
  508.  
  509. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement