List of usage examples for javax.crypto Cipher getInstance
public static final Cipher getInstance(String transformation) throws NoSuchAlgorithmException, NoSuchPaddingException
From source file:TestCipher.java
public static void main(String args[]) throws Exception { Set set = new HashSet(); Random random = new Random(); for (int i = 0; i < 10; i++) { Point point = new Point(random.nextInt(1000), random.nextInt(2000)); set.add(point);//from w w w .j av a 2 s. co m } int last = random.nextInt(5000); // Create Key byte key[] = password.getBytes(); DESKeySpec desKeySpec = new DESKeySpec(key); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); // Create Cipher Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); desCipher.init(Cipher.ENCRYPT_MODE, secretKey); // Create stream FileOutputStream fos = new FileOutputStream("out.des"); BufferedOutputStream bos = new BufferedOutputStream(fos); CipherOutputStream cos = new CipherOutputStream(bos, desCipher); ObjectOutputStream oos = new ObjectOutputStream(cos); // Write objects oos.writeObject(set); oos.writeInt(last); oos.flush(); oos.close(); // Change cipher mode desCipher.init(Cipher.DECRYPT_MODE, secretKey); // Create stream FileInputStream fis = new FileInputStream("out.des"); BufferedInputStream bis = new BufferedInputStream(fis); CipherInputStream cis = new CipherInputStream(bis, desCipher); ObjectInputStream ois = new ObjectInputStream(cis); // Read objects Set set2 = (Set) ois.readObject(); int last2 = ois.readInt(); ois.close(); // Compare original with what was read back int count = 0; if (set.equals(set2)) { System.out.println("Set1: " + set); System.out.println("Set2: " + set2); System.out.println("Sets are okay."); count++; } if (last == last2) { System.out.println("int1: " + last); System.out.println("int2: " + last2); System.out.println("ints are okay."); count++; } if (count != 2) { System.out.println("Problem during encryption/decryption"); } }
From source file:DataStudioCrak.java
public static void main(String[] args) { String company = "labthink"; byte[] companyByteArray = company.getBytes(); byte[] companyByteIntArray = intToByteArray(compute(companyByteArray, companyByteArray.length)); // byte[] ff = "zhulixia".getBytes(); byte[] snByte = new byte[32]; byte[] byte1 = new byte[] { 7, 1 }; byte[] byte2 = "zhaodapengpojiehahahahahaha".getBytes(); byte[] byte3 = new byte[] { 127 }; byte[] snMain = new byte[24]; System.arraycopy(byte1, 0, snMain, 0, 2); System.arraycopy(byte2, 0, snMain, 2, 17); System.arraycopy(companyByteIntArray, 0, snMain, 19, 4); System.arraycopy(byte3, 0, snMain, 23, 1); // 1 - single license,2 - site license ,3 educational license snMain[2] = (byte) 1; int intSn = compute(snMain, snMain.length); System.out.println("intSn=" + intSn); byte[] key1 = "dddd".getBytes(); byte[] key2 = intToByteArray(intSn); byte[] key = new byte[8]; System.arraycopy(key1, 0, key, 0, 4); System.arraycopy(key2, 0, key, 4, 4); byte encodedSnMain[] = new byte[snMain.length]; try {/*from w ww . ja v a 2 s . co m*/ DESKeySpec deskeyspec = new DESKeySpec(key); javax.crypto.SecretKey secretkey = SecretKeyFactory.getInstance("DES").generateSecret(deskeyspec); Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, secretkey); cipher.update(snMain, 0, snMain.length, encodedSnMain); cipher.doFinal(); } catch (Exception ex) { ex.printStackTrace(); } System.arraycopy(key1, 0, snByte, 0, 4); System.arraycopy(key2, 0, snByte, 28, 4); System.arraycopy(encodedSnMain, 0, snByte, 4, 24); char[] snCharArray = Hex.encodeHex(snByte); String sn = new String(snCharArray); System.out.println("sn=" + sn); }
From source file:net.labthink.run.DataStudioCrak.java
public static void main(String[] args) { String company = "Labthink"; byte[] companyByteArray = company.getBytes(); byte[] companyByteIntArray = intToByteArray(compute(companyByteArray, companyByteArray.length)); // byte[] ff = "zhulixia".getBytes(); byte[] snByte = new byte[32]; byte[] byte1 = new byte[] { 7, 1 }; byte[] byte2 = "zhaodapengpojiehahahahahaha".getBytes(); byte[] byte3 = new byte[] { 127 }; byte[] snMain = new byte[24]; System.arraycopy(byte1, 0, snMain, 0, 2); System.arraycopy(byte2, 0, snMain, 2, 17); System.arraycopy(companyByteIntArray, 0, snMain, 19, 4); System.arraycopy(byte3, 0, snMain, 23, 1); // 1 - single license,2 - site license ,3 educational license snMain[2] = (byte) 1; int intSn = compute(snMain, snMain.length); System.out.println("intSn=" + intSn); byte[] key1 = "dddd".getBytes(); byte[] key2 = intToByteArray(intSn); byte[] key = new byte[8]; System.arraycopy(key1, 0, key, 0, 4); System.arraycopy(key2, 0, key, 4, 4); byte encodedSnMain[] = new byte[snMain.length]; try {//from www . ja va2 s. c o m DESKeySpec deskeyspec = new DESKeySpec(key); javax.crypto.SecretKey secretkey = SecretKeyFactory.getInstance("DES").generateSecret(deskeyspec); Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, secretkey); cipher.update(snMain, 0, snMain.length, encodedSnMain); cipher.doFinal(); } catch (Exception ex) { ex.printStackTrace(); } System.arraycopy(key1, 0, snByte, 0, 4); System.arraycopy(key2, 0, snByte, 28, 4); System.arraycopy(encodedSnMain, 0, snByte, 4, 24); char[] snCharArray = Hex.encodeHex(snByte); String sn = new String(snCharArray); System.out.println("sn=" + sn); }
From source file:TripleDES.java
/** * The program. The first argument must be -e, -d, or -g to encrypt, * decrypt, or generate a key. The second argument is the name of a file * from which the key is read or to which it is written for -g. The -e and * -d arguments cause the program to read from standard input and encrypt or * decrypt to standard output.//from w w w . j a va 2 s .com */ public static void main(String[] args) { try { // Check to see whether there is a provider that can do TripleDES // encryption. If not, explicitly install the SunJCE provider. try { Cipher c = Cipher.getInstance("DESede"); } catch (Exception e) { // An exception here probably means the JCE provider hasn't // been permanently installed on this system by listing it // in the $JAVA_HOME/jre/lib/security/java.security file. // Therefore, we have to install the JCE provider explicitly. System.err.println("Installing SunJCE provider."); Provider sunjce = new com.sun.crypto.provider.SunJCE(); Security.addProvider(sunjce); } // This is where we'll read the key from or write it to File keyfile = new File(args[1]); // Now check the first arg to see what we're going to do if (args[0].equals("-g")) { // Generate a key System.out.print("Generating key. This may take some time..."); System.out.flush(); SecretKey key = generateKey(); writeKey(key, keyfile); System.out.println("done."); System.out.println("Secret key written to " + args[1] + ". Protect that file carefully!"); } else if (args[0].equals("-e")) { // Encrypt stdin to stdout SecretKey key = readKey(keyfile); encrypt(key, System.in, System.out); } else if (args[0].equals("-d")) { // Decrypt stdin to stdout SecretKey key = readKey(keyfile); decrypt(key, System.in, System.out); } } catch (Exception e) { System.err.println(e); System.err.println("Usage: java " + TripleDES.class.getName() + " -d|-e|-g <keyfile>"); } }
From source file:com.hernandez.rey.crypto.TripleDES.java
/** * @param args The program. The first argument must be -e, -d, or -g to encrypt, decrypt, or generate a key. The * second argument is the name of a file from which the key is read or to which it is written for -g. The * -e and -d arguments cause the program to read from standard input and encrypt or decrypt to standard * output./*from ww w.j av a 2s . com*/ */ public static void main(final String[] args) { try { // Check to see whether there is a provider that can do TripleDES // encryption. If not, explicitly install the SunJCE provider. try { Cipher.getInstance("DESede"); } catch (final Exception e) { // An exception here probably means the JCE provider hasn't // been permanently installed on this system by listing it // in the $JAVA_HOME/jre/lib/security/java.security file. // Therefore, we have to install the JCE provider explicitly. System.err.println("Installing SunJCE provider."); @SuppressWarnings("restriction") final Provider sunjce = new com.sun.crypto.provider.SunJCE(); Security.addProvider(sunjce); } // This is where we'll read the key from or write it to final File keyfile = new File(args[1]); // Now check the first arg to see what we're going to do if (args[0].equals("-g")) { // Generate a key System.out.print("Generating key. This may take some time..."); System.out.flush(); final SecretKey key = generateKey(); writeKey(key, keyfile); System.out.println("done."); System.out.println("Secret key written to " + args[1] + ". Protect that file carefully!"); } else if (args[0].equals("-e")) { // Encrypt stdin to stdout final SecretKey key = readKey(keyfile); encrypt(key, System.in, System.out); } else if (args[0].equals("-d")) { // Decrypt stdin to stdout final SecretKey key = readKey(keyfile); decrypt(key, System.in, System.out); } } catch (final Exception e) { System.err.println(e); System.err.println("Usage: java " + TripleDES.class.getName() + " -d|-e|-g <keyfile>"); } }
From source file:AESTest.java
public static void main(String[] args) { try {/*from www. j av a 2s .co m*/ if (args[0].equals("-genkey")) { KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom random = new SecureRandom(); keygen.init(random); SecretKey key = keygen.generateKey(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1])); out.writeObject(key); out.close(); } else { int mode; if (args[0].equals("-encrypt")) mode = Cipher.ENCRYPT_MODE; else mode = Cipher.DECRYPT_MODE; ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); Key key = (Key) keyIn.readObject(); keyIn.close(); InputStream in = new FileInputStream(args[1]); OutputStream out = new FileOutputStream(args[2]); Cipher cipher = Cipher.getInstance("AES"); cipher.init(mode, key); crypt(in, out, cipher); in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); } catch (GeneralSecurityException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
From source file:RSATest.java
public static void main(String[] args) { try {// w w w . ja v a 2s .c om if (args[0].equals("-genkey")) { KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); pairgen.initialize(KEYSIZE, random); KeyPair keyPair = pairgen.generateKeyPair(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1])); out.writeObject(keyPair.getPublic()); out.close(); out = new ObjectOutputStream(new FileOutputStream(args[2])); out.writeObject(keyPair.getPrivate()); out.close(); } else if (args[0].equals("-encrypt")) { KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom random = new SecureRandom(); keygen.init(random); SecretKey key = keygen.generateKey(); // wrap with RSA public key ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); Key publicKey = (Key) keyIn.readObject(); keyIn.close(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.WRAP_MODE, publicKey); byte[] wrappedKey = cipher.wrap(key); DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2])); out.writeInt(wrappedKey.length); out.write(wrappedKey); InputStream in = new FileInputStream(args[1]); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, key); crypt(in, out, cipher); in.close(); out.close(); } else { DataInputStream in = new DataInputStream(new FileInputStream(args[1])); int length = in.readInt(); byte[] wrappedKey = new byte[length]; in.read(wrappedKey, 0, length); // unwrap with RSA private key ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); Key privateKey = (Key) keyIn.readObject(); keyIn.close(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.UNWRAP_MODE, privateKey); Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); OutputStream out = new FileOutputStream(args[2]); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); crypt(in, out, cipher); in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); } catch (GeneralSecurityException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
From source file:com.edduarte.protbox.Protbox.java
public static void main(String... args) { // activate debug / verbose mode if (args.length != 0) { List<String> argsList = Arrays.asList(args); if (argsList.contains("-v")) { Constants.verbose = true;//from ww w . jav a 2s . c om } } // use System's look and feel try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { // If the System's look and feel is not obtainable, continue execution with JRE look and feel } // check this is a single instance try { new ServerSocket(1882); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Another instance of Protbox is already running.\n" + "Please close the other instance first.", "Protbox already running", JOptionPane.ERROR_MESSAGE); System.exit(1); } // check if System Tray is supported by this operative system if (!SystemTray.isSupported()) { JOptionPane.showMessageDialog(null, "Your operative system does not support system tray functionality.\n" + "Please try running Protbox on another operative system.", "System tray not supported", JOptionPane.ERROR_MESSAGE); System.exit(1); } // add PKCS11 providers FileFilter fileFilter = new AndFileFilter(new WildcardFileFilter(Lists.newArrayList("*.config")), HiddenFileFilter.VISIBLE); File[] providersConfigFiles = new File(Constants.PROVIDERS_DIR).listFiles(fileFilter); if (providersConfigFiles != null) { for (File f : providersConfigFiles) { try { List<String> lines = FileUtils.readLines(f); String aliasLine = lines.stream().filter(line -> line.contains("alias")).findFirst().get(); lines.remove(aliasLine); String alias = aliasLine.split("=")[1].trim(); StringBuilder sb = new StringBuilder(); for (String s : lines) { sb.append(s); sb.append("\n"); } Provider p = new SunPKCS11(new ReaderInputStream(new StringReader(sb.toString()))); Security.addProvider(p); pkcs11Providers.put(p.getName(), alias); } catch (IOException | ProviderException ex) { if (ex.getMessage().equals("Initialization failed")) { ex.printStackTrace(); String s = "The following error occurred:\n" + ex.getCause().getMessage() + "\n\nIn addition, make sure you have " + "an available smart card reader connected before opening the application."; JTextArea textArea = new JTextArea(s); textArea.setColumns(60); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setSize(textArea.getPreferredSize().width, 1); JOptionPane.showMessageDialog(null, textArea, "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE); System.exit(1); } else { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "Error while setting up PKCS11 provider from configuration file " + f.getName() + ".\n" + ex.getMessage(), "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE); } } } } // adds a shutdown hook to save instantiated directories into files when the application is being closed Runtime.getRuntime().addShutdownHook(new Thread(Protbox::exit)); // get system tray and run tray applet tray = SystemTray.getSystemTray(); SwingUtilities.invokeLater(() -> { if (Constants.verbose) { logger.info("Starting application"); } //Start a new TrayApplet object trayApplet = TrayApplet.getInstance(); }); // prompts the user to choose which provider to use ProviderListWindow.showWindow(Protbox.pkcs11Providers.keySet(), providerName -> { // loads eID token eIDTokenLoadingWindow.showPrompt(providerName, (returnedUser, returnedCertificateData) -> { user = returnedUser; certificateData = returnedCertificateData; // gets a password to use on the saved registry files (for loading and saving) final AtomicReference<Consumer<SecretKey>> consumerHolder = new AtomicReference<>(null); consumerHolder.set(password -> { registriesPasswordKey = password; try { // if there are serialized files, load them if they can be decoded by this user's private key final List<SavedRegistry> serializedDirectories = new ArrayList<>(); if (Constants.verbose) { logger.info("Reading serialized registry files..."); } File[] registryFileList = new File(Constants.REGISTRIES_DIR).listFiles(); if (registryFileList != null) { for (File f : registryFileList) { if (f.isFile()) { byte[] data = FileUtils.readFileToByteArray(f); try { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, registriesPasswordKey); byte[] registryDecryptedData = cipher.doFinal(data); serializedDirectories.add(new SavedRegistry(f, registryDecryptedData)); } catch (GeneralSecurityException ex) { if (Constants.verbose) { logger.info("Inserted Password does not correspond to " + f.getName()); } } } } } // if there were no serialized directories, show NewDirectory window to configure the first folder if (serializedDirectories.isEmpty() || registryFileList == null) { if (Constants.verbose) { logger.info("No registry files were found: running app as first time!"); } NewRegistryWindow.start(true); } else { // there were serialized directories loadRegistry(serializedDirectories); trayApplet.repaint(); showTrayApplet(); } } catch (AWTException | IOException | GeneralSecurityException | ReflectiveOperationException | ProtboxException ex) { JOptionPane.showMessageDialog(null, "The inserted password was invalid! Please try another one!", "Invalid password!", JOptionPane.ERROR_MESSAGE); insertPassword(consumerHolder.get()); } }); insertPassword(consumerHolder.get()); }); }); }
From source file:Main.java
public static byte[] decrypt(byte[] key, byte[] input) throws Exception { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES")); byte[] decrypted = cipher.doFinal(input); return decrypted; }
From source file:Main.java
public static byte[] encrypt(byte[] key, byte[] input) throws Exception { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES")); byte[] encrypted = cipher.doFinal(input); return encrypted; }