Advertisement
Guest User

cR

a guest
Oct 23rd, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.39 KB | None | 0 0
  1. package ivb511.crypto;
  2.  
  3. import javax.crypto.*;
  4. import java.io.*;
  5. import java.security.*;
  6. import java.security.cert.CertificateEncodingException;
  7. import java.security.cert.CertificateException;
  8. import java.security.cert.CertificateFactory;
  9. import java.security.cert.X509Certificate;
  10.  
  11. public class JavaCrypto {
  12.     private final static int EXIT = 11;
  13.     private static KeyStore keyStore;
  14.     private static KeyGenerator secretKeyGenerator;
  15.     private static Cipher cipher;
  16.     private static Cipher keyWrapper;
  17.     private static Signature sig;
  18.     private static BufferedReader br;
  19.  
  20.     static {
  21.         try {
  22.             br = new BufferedReader(new InputStreamReader(System.in));
  23.             secretKeyGenerator = KeyGenerator.getInstance("RC4");
  24.             secretKeyGenerator.init(new SecureRandom());
  25.             keyWrapper = Cipher.getInstance("RSA");
  26.             cipher = Cipher.getInstance("RC4");
  27.             keyStore = KeyStore.getInstance("JCEKS");
  28.             sig = Signature.getInstance("MD5withRSA");
  29.         } catch (NoSuchAlgorithmException | KeyStoreException | NoSuchPaddingException e) {
  30.             e.printStackTrace();
  31.         }
  32.     }
  33.  
  34.     public static void main(String[] args) {
  35.         int menuItem = 0;
  36.         do try {
  37.             switch (menuItem = getMenuItem()) {
  38.                 case 1:
  39.                     createKeyStore();
  40.                     break;
  41.                 case 2:
  42.                     loadKeyStore();
  43.                     break;
  44.                 case 3:
  45.                     saveKeyStore();
  46.                     break;
  47.                 case 4:
  48.                     importCertificate();
  49.                     break;
  50.                 case 5:
  51.                     exportCertificate();
  52.                     break;
  53.                 case 6:
  54.                     createSymmetricKey();
  55.                     break;
  56.                 case 7:
  57.                     exportSymmetricKey();
  58.                     break;
  59.                 case 8:
  60.                     importSymmetricKey();
  61.                     break;
  62.                 case 9:
  63.                     encryptAndSignMessage();
  64.                     break;
  65.                 case 10:
  66.                     decryptCiphertexrAndVerifySignature();
  67.                     break;
  68.                 case 11:
  69.                     break;
  70.                 default:
  71.                     System.out.println("Не верно выбрано действие");
  72.  
  73.             }
  74.  
  75.         } catch (Exception e) {
  76.             e.printStackTrace();
  77.         }
  78.         while (menuItem != EXIT);
  79.     }
  80.  
  81.     private static void createSymmetricKey() throws IOException, KeyStoreException {
  82.         String keyAlias = getStr("\nType key alias, please");
  83.         char[] password = getStr("Type password, please").toCharArray();
  84.         SecretKey secretKey = secretKeyGenerator.generateKey();
  85.         keyStore.setEntry(keyAlias, new KeyStore.SecretKeyEntry(secretKey), new KeyStore.PasswordProtection(password));
  86.         System.out.println("\nThe symmetric key was successfully created. \n");
  87.     }
  88.  
  89.     private static void decryptCiphertexrAndVerifySignature() throws IOException, SignatureException, InvalidKeyException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
  90.         String skAlias = getStr("Type symmetric key alias, please");
  91.         char[] skPassword = getStr("Type symmetric key alias, please").toCharArray();
  92.         String ciphertextFileName = getStr("Type name of file to read ciphertext from, please");
  93.         String signatureFileName = getStr("Type signature file name, please");
  94.         String certAlias = getStr("Type certificate alias to verify signature, please");
  95.         SecretKey secretKey = (SecretKey) keyStore.getKey(skAlias, skPassword);
  96.         cipher.init(Cipher.DECRYPT_MODE, secretKey);
  97.         FileInputStream fis = new FileInputStream(ciphertextFileName);
  98.         byte[] message = new byte[fis.available()];
  99.         CipherInputStream cis = new CipherInputStream(fis, cipher);
  100.         cis.read(message);
  101.         System.out.println("The message is: " + new String(message) + ".");
  102.         cis.close();
  103.  
  104.         fis = new FileInputStream(signatureFileName);
  105.         byte[] ds = new byte[fis.available()];
  106.         fis.read(ds);
  107.         fis.close();
  108.  
  109.         X509Certificate cert = (X509Certificate) keyStore.getCertificate(certAlias);
  110.         sig.initVerify(cert.getPublicKey());
  111.         sig.update(message);
  112.         System.out.println(sig.verify(ds) ? "The signature matches." : "The signature does not match.");
  113.  
  114.     }
  115.  
  116.     private static void encryptAndSignMessage() throws IOException, InvalidKeyException, SignatureException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
  117.         String keyAlias = getStr("\nType symmetric key alias, please");
  118.         char[] skPassword = getStr("Type symmetric key password, please").toCharArray();
  119.         String message = getStr("Type your message to be encrypted, please");
  120.         String ciphertextFileName = getStr("Type name of file to save encrypted message to, please");
  121.         String prvkAlias = getStr("Type private key alias to sign the message, please");
  122.         char[] prvkPassword = getStr("Type private key password, please").toCharArray();
  123.         String signatureFileName = getStr("Type name of file to save signature, please");
  124.         SecretKey secretKey = (SecretKey) keyStore.getKey(keyAlias, skPassword);
  125.         cipher.init(Cipher.ENCRYPT_MODE, secretKey);
  126.         CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(ciphertextFileName), cipher);
  127.         cos.write(message.getBytes());
  128.         cos.flush();
  129.         cos.close();
  130.         PrivateKey privateKey = (PrivateKey) keyStore.getKey(prvkAlias, prvkPassword);
  131.         sig.initSign(privateKey);
  132.         sig.update(message.getBytes());
  133.         byte[] ds = sig.sign();
  134.         FileOutputStream fos = new FileOutputStream(signatureFileName);
  135.         fos.write(ds);
  136.         fos.flush();
  137.         fos.close();
  138.     }
  139.  
  140.  
  141.     private static void importSymmetricKey() throws NoSuchAlgorithmException, InvalidKeyException, IOException, UnrecoverableKeyException, KeyStoreException {
  142.         String skFileName = getStr("\nType file name to import from, please");
  143.         String prvkAlias = getStr("Type private key alias, please");
  144.         char[] prvkPassword = getStr("Type private key alias, please").toCharArray();
  145.         String skAlias = getStr("Type alias to store symmetric key, please");
  146.         char[] skPassword = getStr("Type symmetric key password, please").toCharArray();
  147.         FileInputStream fis = new FileInputStream(skFileName);
  148.         byte[] wrappedKey = new byte[fis.available()];
  149.         fis.read();
  150.         fis.close();
  151.         keyWrapper.init(Cipher.UNWRAP_MODE, keyStore.getKey(prvkAlias, prvkPassword));
  152.         SecretKey secretKey = (SecretKey) keyWrapper.unwrap(wrappedKey, "RC4", Cipher.SECRET_KEY);
  153.         keyStore.setEntry(skAlias, new KeyStore.SecretKeyEntry(secretKey), new KeyStore.PasswordProtection(skPassword));
  154.         System.out.println("\nThe symmetric key was successfully imported. \n");
  155.  
  156.     }
  157.  
  158.  
  159.     private static void exportSymmetricKey() throws IOException, KeyStoreException, InvalidKeyException, IllegalBlockSizeException, UnrecoverableKeyException, NoSuchAlgorithmException {
  160.         String skAlias = getStr("\nType symmetric key alias, please");
  161.         char[] password = getStr("Type symmetric key password, please").toCharArray();
  162.         String certAlias = getStr("Type certificate alias, please");
  163.         String skFileName = getStr("Type name of a file to export the symmetric key, please");
  164.         SecretKey key = (SecretKey) keyStore.getKey(skAlias, password);
  165.         X509Certificate cert = (X509Certificate) keyStore.getCertificate(certAlias);
  166.         keyWrapper.init(Cipher.WRAP_MODE, cert.getPublicKey());
  167.         byte wrappedKey[] = keyWrapper.wrap(key);
  168.         FileOutputStream fos = new FileOutputStream(skFileName);
  169.         fos.write(wrappedKey);
  170.         fos.flush();
  171.         fos.close();
  172.     }
  173.  
  174.     private static void exportCertificate() throws IOException, KeyStoreException, CertificateEncodingException {
  175.         String alias = getStr("\nType certificate alias, please");
  176.         String certFileName = getStr("Type certificate file name, please");
  177.         X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
  178.         FileOutputStream fos = new FileOutputStream(certFileName);
  179.         fos.write(cert.getEncoded());
  180.         fos.close();
  181.         System.out.println("\nThe certificate was successfully exported. \n");
  182.  
  183.     }
  184.  
  185.     private static void importCertificate() throws CertificateException, IOException, KeyStoreException {
  186.         String fileName = getStr("\nType file name, please");
  187.         String alias = getStr("\nType file name, please");
  188.         FileInputStream fis = new FileInputStream(fileName);
  189.         CertificateFactory cf = CertificateFactory.getInstance("X.509");
  190.         X509Certificate cert = (X509Certificate) cf.generateCertificate(fis);
  191.         fis.close();
  192.         keyStore.setCertificateEntry(alias, cert);
  193.         System.out.println("\nThe certificate was successfully imported. \n");
  194.     }
  195.  
  196.  
  197.     private static void saveKeyStore() throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException {
  198.         String fileName = getStr("\nType file name, please");
  199.         char[] password = getStr("Type the keystore password,please").toCharArray();
  200.         FileOutputStream fos = new FileOutputStream(fileName);
  201.         keyStore.store(fos, password);
  202.         fos.flush();
  203.         fos.close();
  204.         System.out.println("\nThe keystore was successfully saved. \n");
  205.     }
  206.  
  207.     private static void loadKeyStore() throws IOException, CertificateException, NoSuchAlgorithmException {
  208.         String fileName = getStr("\nType file name, please");
  209.         char[] password = getStr("Type the keystore password, please").toCharArray();
  210.         FileInputStream fis = new FileInputStream(fileName);
  211.         keyStore.load(fis, password);
  212.         fis.close();
  213.         System.out.println("\nThe keystore was succesfully loaded. \n");
  214.     }
  215.  
  216.     private static void createKeyStore() throws CertificateException, NoSuchAlgorithmException, IOException {
  217.         char[] password = getStr("\nType the keystore password, please").toCharArray();
  218.         keyStore.load(null, password);
  219.         System.out.println("\nThe new keystore was successfully created. \n");
  220.     }
  221.  
  222.     private static int getMenuItem() throws Exception {
  223.         System.out.println("Menu");
  224.         System.out.println("---------------------");
  225.         System.out.println("1. Create keystore");
  226.         System.out.println("2. Load keystore");
  227.         System.out.println("3. Save keystore");
  228.         System.out.println("4. Import certificate");
  229.         System.out.println("5. Export certificate");
  230.         System.out.println("6. Create symmetric key");
  231.         System.out.println("7. Export symetric key");
  232.         System.out.println("8. Import symmetric key");
  233.         System.out.println("9. Encrypt and sign message");
  234.         System.out.println("10. Decrypt ciphertext and verify signature");
  235.         System.out.println("11. Exit");
  236.         System.out.println("---------------------");
  237.         return Integer.parseInt(getStr("Type menu item, please"));
  238.     }
  239.  
  240.     private static String getStr(String s) throws IOException {
  241.         System.out.println(s + ": ");
  242.         return br.readLine();
  243.     }
  244. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement