public boolean generateKeys() { PublicKey keyPub; PrivateKey keyPri; SecureRandom rand; Security.addProvider(new ABAProvider()); rand = new SecureRandom(); rand.setSeed(System.currentTimeMillis()); try { KeyPairGenerator fact; KeyPair keyPair; fact = KeyPairGenerator.getInstance("RSA", "ABA"); fact.initialize(1024, rand); keyPair = fact.generateKeyPair(); keyPub = keyPair.getPublic(); keyPri = keyPair.getPrivate(); pubKey = bytesToHexStr(keyPub.getEncoded()); priKey = bytesToHexStr(keyPri.getEncoded()); } catch (Exception e) { return false; } return true; }
private static boolean checkKeysEqual(PublicKey pk1, PublicKey pk2) { // first, they should have the same format // second, their encoded form must be the same // assert(pk1 != null); // assert(pk2 != null); String format1 = pk1.getFormat(); String format2; if ((pk2 == null) || (((format2 = pk2.getFormat()) != null) ^ (format1 != null)) || ((format1 != null) && !format1.equals(format2))) { return false; } return Arrays.equals(pk1.getEncoded(), pk2.getEncoded()); }
public static byte[] func_75895_a(String p_75895_0_, PublicKey p_75895_1_, SecretKey p_75895_2_) { try { return func_75893_a( "SHA-1", new byte[][] { p_75895_0_.getBytes("ISO_8859_1"), p_75895_2_.getEncoded(), p_75895_1_.getEncoded() }); } catch (UnsupportedEncodingException unsupportedencodingexception) { unsupportedencodingexception.printStackTrace(); } return null; }
public byte[] createPublicKey() throws CryptoException { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM); keyGen.initialize(DH_SPEC); KeyPair keypair = keyGen.generateKeyPair(); privateKey = keypair.getPrivate(); PublicKey publicKey = keypair.getPublic(); return publicKey.getEncoded(); } catch (NoSuchAlgorithmException e) { throw new CryptoException(CorePlugin.Event.TEIID10001, e); } catch (InvalidAlgorithmParameterException e) { throw new CryptoException(CorePlugin.Event.TEIID10002, e); } }
// internal implementation of translateKey() for public keys. See JCA doc private PublicKey translatePublicKey(PublicKey key) throws InvalidKeyException { if (key instanceof RSAPublicKey) { if (key instanceof RSAPublicKeyImpl) { return key; } RSAPublicKey rsaKey = (RSAPublicKey) key; try { return new RSAPublicKeyImpl(rsaKey.getModulus(), rsaKey.getPublicExponent()); } catch (RuntimeException e) { // catch providers that incorrectly implement RSAPublicKey throw new InvalidKeyException("Invalid key", e); } } else if ("X.509".equals(key.getFormat())) { byte[] encoded = key.getEncoded(); return new RSAPublicKeyImpl(encoded); } else { throw new InvalidKeyException( "Public keys must be instance " + "of RSAPublicKey or have X.509 encoding"); } }
/* * 产生RSA公私钥对 */ public static void genRSAKeyPair() { KeyPairGenerator rsaKeyGen = null; KeyPair rsaKeyPair = null; try { System.out.println("Generating a pair of RSA key ... "); rsaKeyGen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); random.setSeed(System.currentTimeMillis()); // rsaKeyGen.initialize(1024, random); rsaKeyGen.initialize(1024); rsaKeyPair = rsaKeyGen.genKeyPair(); PublicKey rsaPublic = rsaKeyPair.getPublic(); PrivateKey rsaPrivate = rsaKeyPair.getPrivate(); System.out.println("公钥:" + bytesToHexStr(rsaPublic.getEncoded())); System.out.println("私钥:" + bytesToHexStr(rsaPrivate.getEncoded())); System.out.println("1024-bit RSA key GENERATED."); } catch (Exception e) { System.out.println("genRSAKeyPair:" + e); } }
public static void main(String[] args) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(1024, random); KeyPair pair = keyGen.generateKeyPair(); PrivateKey priv = pair.getPrivate(); PublicKey pub = pair.getPublic(); byte[] encPriv = priv.getEncoded(); FileOutputStream privfos = new FileOutputStream("DSAPrivateKey.key"); privfos.write(encPriv); privfos.close(); byte[] encPub = pub.getEncoded(); FileOutputStream pubfos = new FileOutputStream("DSAPublicKey.key"); pubfos.write(encPub); pubfos.close(); } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) throws Exception { // prompt user to enter a port number System.out.print("Enter the port number: "); Scanner scan = new Scanner(System.in); int port = scan.nextInt(); scan.nextLine(); System.out.print("Enter the host name: "); String hostName = scan.nextLine(); // Initialize a key pair generator with the SKIP parameters we sepcified, and genrating a pair // This will take a while: 5...15 seconrds System.out.println("Generating a Diffie-Hellman keypair: "); KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH"); kpg.initialize(PARAMETER_SPEC); KeyPair keyPair = kpg.genKeyPair(); System.out.println("key pair has been made..."); // one the key pair has been generated, we want to listen on // a given port for a connection to come in // once we get a connection, we will get two streams, One for input // and one for output // open a port and wait for a connection ServerSocket ss = new ServerSocket(port); System.out.println("Listeining on port " + port + " ..."); Socket socket = ss.accept(); // use to output and input primitive data type DataOutputStream out = new DataOutputStream(socket.getOutputStream()); // next thing to do is send our public key and receive client's // this corresponds to server step 3 and step 4 in the diagram System.out.println("Sending my public key..."); byte[] keyBytes = keyPair.getPublic().getEncoded(); out.writeInt(keyBytes.length); out.write(keyBytes); System.out.println("Server public key bytes: " + CryptoUtils.toHex(keyBytes)); // receive the client's public key System.out.println("Receiving client's public key..."); DataInputStream in = new DataInputStream(socket.getInputStream()); keyBytes = new byte[in.readInt()]; in.readFully(keyBytes); // create client's public key KeyFactory kf = KeyFactory.getInstance("DH"); X509EncodedKeySpec x509Spec = new X509EncodedKeySpec(keyBytes); PublicKey clientPublicKey = kf.generatePublic(x509Spec); // print out client's public key bytes System.out.println( "Client public key bytes: " + CryptoUtils.toHex(clientPublicKey.getEncoded())); // we can now use the client's public key and // our own private key to perform the key agreement System.out.println("Performing the key agreement ... "); KeyAgreement ka = KeyAgreement.getInstance("DH"); ka.init(keyPair.getPrivate()); ka.doPhase(clientPublicKey, true); // in a chat application, each character is sendt over the wire, separetly encrypted, // Instead of using ECB, we are goin to use CFB, with a block size of 8 bits(1byte) // to send each character. We will encrypt the same character in a different way // each time. But in order to use CFB8, we need an IVof 8 bytes. We will create // that IV randomly and and send it to the client. It doesn't matter if somoene // eavesdrops on the IV when it is sent over the wire. it's not sensitive info // creating the IV and sending it corresponds to step 6 and 7 byte[] iv = new byte[8]; SecureRandom sr = new SecureRandom(); sr.nextBytes(iv); out.write(iv); // we generate the secret byte array we share with the client and use it // to create the session key (Step 8) byte[] sessionKeyBytes = ka.generateSecret(); // create the session key SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede"); DESedeKeySpec DESedeSpec = new DESedeKeySpec(sessionKeyBytes); SecretKey sessionKey = skf.generateSecret(DESedeSpec); // printout session key bytes System.out.println("Session key bytes: " + CryptoUtils.toHex(sessionKey.getEncoded())); // now use tha that session key and IV to create a CipherInputStream. We will use them to read // all character // that are sent to us by the client System.out.println("Creating the cipher stream ..."); Cipher decrypter = Cipher.getInstance("DESede/CFB8/NoPadding"); IvParameterSpec spec = new IvParameterSpec(iv); decrypter.init(Cipher.DECRYPT_MODE, sessionKey, spec); CipherInputStream cipherIn = new CipherInputStream(socket.getInputStream(), decrypter); // we just keep reading the input and print int to the screen, until -1 sent over int theCharacter = 0; theCharacter = cipherIn.read(); while (theCharacter != -1) { System.out.print((char) theCharacter); theCharacter = cipherIn.read(); } // once -1 is received we want to close up our stream and exit cipherIn.close(); in.close(); out.close(); socket.close(); }
public boolean connect(String username, String weakSecret, final String server, final int port) { System.out.println("attempting to connect"); try { sock = new Socket(); sock.connect(new InetSocketAddress(server, port)); output = new ObjectOutputStream(sock.getOutputStream()); input = new ObjectInputStream(sock.getInputStream()); output.writeObject(username); // do DH exchange and agree on starting message index try { if (weakSecret != null) // group server connect { HashMap<String, SecretKey> secretKeys = DHKeyExchange.generateSecretKeyWithWeakSecret(username, weakSecret, input, output); if (secretKeys == null) throw new Exception("Unable to verify server"); encryptionKey = secretKeys.get("encryptionKey"); signingKey = secretKeys.get("signingKey"); } else // file server connect { PublicKey fileServerPublicKey = (PublicKey) input.readObject(); // read in public key File savedKeys = new File("savedkeys.bin"); ArrayList<PublicKey> knownKeys = new ArrayList<PublicKey>(); if (savedKeys.exists()) { ObjectInputStream in = new ObjectInputStream(new FileInputStream(savedKeys)); knownKeys = (ArrayList<PublicKey>) in.readObject(); } if (!knownKeys.contains(fileServerPublicKey)) // prompt the user to verify the key { MessageDigest sha = MessageDigest.getInstance("SHA-1"); byte[] digest = sha.digest(fileServerPublicKey.getEncoded()); System.out.println("RSA key fingerprint is " + getFingerprint(digest)); System.out.println( "Please verify this is correct by contacting the file server owner."); System.out.println( "Do you want to add this key to your list of saved servers? (yes/no)"); Scanner scanner = new Scanner(System.in); String answer = scanner.nextLine(); if (answer.toLowerCase().equals("yes")) { knownKeys.add(fileServerPublicKey); savedKeys.delete(); savedKeys.createNewFile(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(savedKeys)); out.writeObject(knownKeys); out.flush(); out.close(); output.writeObject("yes"); } else { output.writeObject("no"); System.out.println("Exiting"); System.exit(0); } } else // accpet the key without prompt output.writeObject("yes"); generateRSAKeypair(); output.writeObject(publicKey); HashMap<String, SecretKey> secretKeys = DHKeyExchange.generateSecretKeySignedExchange( input, output, privateKey, fileServerPublicKey); if (secretKeys == null) throw new Exception("Unable to verify server"); encryptionKey = secretKeys.get("encryptionKey"); signingKey = secretKeys.get("signingKey"); } encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); MessageDigest sha = MessageDigest.getInstance("SHA-1"); byte[] key = sha.digest(encryptionKey.getEncoded()); key = Arrays.copyOf(key, 16); // use only first 128 bit SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); encryptCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(ivBytes)); decryptCipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(ivBytes)); BigInteger R = new BigInteger(128, new SecureRandom()); output.writeObject(encryptCipher.doFinal(R.toByteArray())); BigInteger start = new BigInteger(decryptCipher.doFinal((byte[]) input.readObject())); if (start.compareTo(R) < 0) throw new Exception("Invalid message index from server"); else messageIndex = start.add(BigInteger.ONE); } catch (Exception ex) { System.out.println("Failed to connect: " + ex.getMessage()); // if anything fails, we are not connected sock = null; return false; } } catch (IOException ex) { return false; } return true; }