public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Misc func = new Misc(); // initialize the key generator (KG) and generate the public/private key pair SecureRandom random = new SecureRandom(); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC"); generator.initialize(1024, random); KeyPair pair = generator.generateKeyPair(); /* initialize KG for digital signature and generate public/private keys for digital signatures It is generally not recommended to use the same public/private key pair for both encryption and digital signatures */ KeyPairGenerator generatorTwo = KeyPairGenerator.getInstance("RSA"); generatorTwo.initialize(1024); KeyPair sigKeyPair = generatorTwo.generateKeyPair(); byte[] sigPubKey = sigKeyPair.getPublic().getEncoded(); byte[] sigPrivKey = sigKeyPair.getPrivate().getEncoded(); byte[] pubKey = pair.getPublic().getEncoded(); byte[] privKey = pair.getPrivate().getEncoded(); // output the generated keys func.outputText(func.byteToHex(sigPubKey), "alice-dspk.txt"); func.outputText(func.byteToHex(sigPrivKey), "alice-dspvk.txt"); func.outputText(func.byteToHex(pubKey), "bob-pkepk.txt"); func.outputText(func.byteToHex(privKey), "bob-pkepvk.txt"); // clear sensitive data func.clear(sigPubKey); func.clear(sigPrivKey); func.clear(pubKey); func.clear(privKey); }
public byte[] getE() throws Exception { if (e == null) { DHParameterSpec dhSkipParamSpec = new DHParameterSpec(p, g); myKpairGen.initialize(dhSkipParamSpec); KeyPair myKpair = myKpairGen.generateKeyPair(); myKeyAgree.init(myKpair.getPrivate()); // BigInteger x=((javax.crypto.interfaces.DHPrivateKey)(myKpair.getPrivate())).getX(); byte[] myPubKeyEnc = myKpair.getPublic().getEncoded(); e = ((javax.crypto.interfaces.DHPublicKey) (myKpair.getPublic())).getY(); e_array = e.toByteArray(); } return e_array; }
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; }
public void main(Provider p) throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", p); kpg.initialize(512); KeyPair kp = kpg.generateKeyPair(); PrivateKey privateKey = kp.getPrivate(); PublicKey publicKey = kp.getPublic(); Signature sig = Signature.getInstance("MD5withRSA", p); byte[] data = new byte[10 * 1024]; new Random().nextBytes(data); sig.initSign(privateKey); sig.initSign(privateKey); sig.update(data); sig.initSign(privateKey); sig.update(data); byte[] signature = sig.sign(); sig.update(data); sig.initSign(privateKey); sig.update(data); sig.sign(); sig.sign(); sig.initSign(privateKey); sig.sign(); System.out.println("All tests passed"); }
/** * Create a self-signed X.509 Certificate. From * http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html. * * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB" * @param pair the KeyPair * @param days how many days from now the Certificate is valid for * @param algorithm the signing algorithm, eg "SHA1withRSA" * @return the self-signed certificate * @throws CertificateException thrown if a security error or an IO error ocurred. */ public static X509Certificate generateCertificate( String dn, KeyPair pair, int days, String algorithm) throws CertificateException { try { Security.addProvider(new BouncyCastleProvider()); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam); X500Name name = new X500Name(dn); Date from = new Date(); Date to = new Date(from.getTime() + days * 86400000L); BigInteger sn = new BigInteger(64, new SecureRandom()); X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo); X509CertificateHolder certificateHolder = v1CertGen.build(sigGen); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder); } catch (CertificateException ce) { throw ce; } catch (Exception e) { throw new CertificateException(e); } }
public static void main(String[] args) { try { AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DSA"); paramGen.init(1024); AlgorithmParameters params = paramGen.generateParameters(); DSAParameterSpec dsaParameterSpec = params.getParameterSpec(DSAParameterSpec.class); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA"); keyPairGenerator.initialize(dsaParameterSpec); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); saveKey("BpubKey", publicKey); saveKey("BprivKey", privateKey); } catch (NoSuchAlgorithmException | InvalidParameterSpecException | InvalidAlgorithmParameterException e) { e.printStackTrace(); } }
public void run() { try { ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); BigInteger bg = dhSpec.getG(); BigInteger bp = dhSpec.getP(); oos.writeObject(bg); oos.writeObject(bp); KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH"); kpg.initialize(1024); KeyPair kpa = (KeyPair) ois.readObject(); KeyAgreement dh = KeyAgreement.getInstance("DH"); KeyPair kp = kpg.generateKeyPair(); oos.writeObject(kp); dh.init(kp.getPrivate()); Key pk = dh.doPhase(kpa.getPublic(), true); MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); byte[] rawbits = sha256.digest(dh.generateSecret()); Cipher c = Cipher.getInstance(CIPHER_MODE); SecretKey key = new SecretKeySpec(rawbits, 0, 16, "AES"); byte ivbits[] = (byte[]) ois.readObject(); IvParameterSpec iv = new IvParameterSpec(ivbits); c.init(Cipher.DECRYPT_MODE, key, iv); Mac m = Mac.getInstance("HmacSHA1"); SecretKey mackey = new SecretKeySpec(rawbits, 16, 16, "HmacSHA1"); m.init(mackey); byte ciphertext[], cleartext[], mac[]; try { while (true) { ciphertext = (byte[]) ois.readObject(); mac = (byte[]) ois.readObject(); if (Arrays.equals(mac, m.doFinal(ciphertext))) { cleartext = c.update(ciphertext); System.out.println(ct + " : " + new String(cleartext, "UTF-8")); } else { // System.exit(1); System.out.println(ct + "error"); } } } catch (EOFException e) { cleartext = c.doFinal(); System.out.println(ct + " : " + new String(cleartext, "UTF-8")); System.out.println("[" + ct + "]"); } finally { if (ois != null) ois.close(); if (oos != null) oos.close(); } } catch (Exception e) { e.printStackTrace(); } }
public boolean createSelfSignedKeystore( String cn, String keystoreFile, String keystorePassword, String privateKeyPassword, String privateKeyAlias) { KeyStore ks = null; try { ks = KeyStore.getInstance("JKS"); ks.load(null, null); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); keyGen.initialize(1024, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); PrivateKey privkey = keypair.getPrivate(); PublicKey pubkey = keypair.getPublic(); Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>(); Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>(); ordering.add(X509Name.CN); attrs.put(X509Name.CN, cn); X509Name issuerDN = new X509Name(ordering, attrs); X509Name subjectDN = new X509Name(ordering, attrs); Date validFrom = new Date(); validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000)); Date validTo = new Date(); validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator x509 = new X509V3CertificateGenerator(); x509.setSignatureAlgorithm("SHA1withDSA"); x509.setIssuerDN(issuerDN); x509.setSubjectDN(subjectDN); x509.setPublicKey(pubkey); x509.setNotBefore(validFrom); x509.setNotAfter(validTo); x509.setSerialNumber(new BigInteger(128, new Random())); X509Certificate[] cert = new X509Certificate[1]; cert[0] = x509.generate(privkey, "BC"); java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1]; chain[0] = cert[0]; ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert); ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain); ks.store(new FileOutputStream(keystoreFile), keystorePassword.toCharArray()); String IDP_RFC_CERT = "WEB-INF/guanxi_idp/keystore/guanxi_idp_cert.txt"; PEMWriter pemWriter = new PEMWriter(new FileWriter(servletContext.getRealPath(IDP_RFC_CERT))); pemWriter.writeObject(cert[0]); pemWriter.close(); return true; } catch (Exception se) { return false; } }
/** * Creates a file server. Uses aConnectedSocket to create input/output stream readers to * communicate with a client. * * @param aConnectedSocket Socket through which to communicated with a client. */ public FileServer(Socket aConnectedSocket) throws IOException, NoSuchAlgorithmException { connectedSocket = aConnectedSocket; // Set up input/output streams inFromClient = new BufferedReader(new InputStreamReader(connectedSocket.getInputStream())); outToClient = new DataOutputStream(connectedSocket.getOutputStream()); // generate keys KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); privateKey = keyPair.getPrivate(); publicKey = keyPair.getPublic(); }
private void generateRSAKeypair() { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair keys = keyGen.generateKeyPair(); publicKey = keys.getPublic(); privateKey = keys.getPrivate(); } catch (Exception e) { e.printStackTrace(); } }
/** Generate a Diffie-Hellman keypair of the specified size. */ DHCrypt(int keyLength, SecureRandom random) { try { KeyPairGenerator kpg = JsseJce.getKeyPairGenerator("DiffieHellman"); kpg.initialize(keyLength, random); KeyPair kp = kpg.generateKeyPair(); privateKey = kp.getPrivate(); DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic()); publicValue = spec.getY(); modulus = spec.getP(); base = spec.getG(); } catch (GeneralSecurityException e) { throw new RuntimeException("Could not generate DH keypair", e); } }
public static void main(String[] args) throws Exception { // // verifica args e recebe o texto plano if (args.length != 1) { System.err.println("Usage: java DigitalSignatureExample text"); System.exit(1); } byte[] plainText = args[0].getBytes("UTF8"); // // gera o par de chaves RSA System.out.println("\nStart generating RSA key"); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); KeyPair key = keyGen.generateKeyPair(); System.out.println("Finish generating RSA key"); // // define um objeto signature para utilizar MD5 e RSA // e assina o texto plano com a chave privada, // o provider utilizado tambem eh impresso Signature sig = Signature.getInstance("MD5WithRSA"); sig.initSign(key.getPrivate()); sig.update(plainText); byte[] signature = sig.sign(); System.out.println(sig.getProvider().getInfo()); System.out.println("\nSignature:"); // converte o signature para hexadecimal StringBuffer buf = new StringBuffer(); for (int i = 0; i < signature.length; i++) { String hex = Integer.toHexString(0x0100 + (signature[i] & 0x00FF)).substring(1); buf.append((hex.length() < 2 ? "0" : "") + hex); } // imprime o signature em hexadecimal System.out.println(buf.toString()); // // verifica a assinatura com a chave publica System.out.println("\nStart signature verification"); sig.initVerify(key.getPublic()); sig.update(plainText); try { if (sig.verify(signature)) { System.out.println("Signature verified"); } else System.out.println("Signature failed"); } catch (SignatureException se) { System.out.println("Singature failed"); } }
/** * Generate a Diffie-Hellman keypair using the specified parameters. * * @param modulus the Diffie-Hellman modulus P * @param base the Diffie-Hellman base G */ DHCrypt(BigInteger modulus, BigInteger base, SecureRandom random) { this.modulus = modulus; this.base = base; try { KeyPairGenerator kpg = JsseJce.getKeyPairGenerator("DiffieHellman"); DHParameterSpec params = new DHParameterSpec(modulus, base); kpg.initialize(params, random); KeyPair kp = kpg.generateKeyPair(); privateKey = kp.getPrivate(); DHPublicKeySpec spec = getDHPublicKeySpec(kp.getPublic()); publicValue = spec.getY(); } catch (GeneralSecurityException e) { throw new RuntimeException("Could not generate DH keypair", e); } }
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); } }
/** * Creates an X509 version3 certificate * * @param algorithm (e.g RSA, DSA, etc...) * @param bits Cet strength e.g 1024 * @param issuer Issuer string e.g "O=Grid,OU=OGSA,CN=ACME" * @param subject Subject string e.g "O=Grid,OU=OGSA,CN=John Doe" * @param months time to live * @param outPrivKey OutputStream to the private key in PKCS#8 format (Note: this key will not be * encrypted) * @return X509 V3 Certificate * @throws GeneralSecurityException */ public static X509Certificate createX509Cert( String algorithm, int bits, String issuer, String subject, int months, OutputStream outPrivKey, String sigAlg, String pwd) throws GeneralSecurityException, IOException { // String sigAlg = "SHA1WithRSAEncryption"; // Priv key is in PKCS#8 format KeyPair kp = CertUtil.generateKeyPair(algorithm, bits); // must convert from PKCS#8 to PKCS#1 to encrypt with BouncyCastleOpenSSLKey // Priv key must be DER encoded key data in PKCS#1 format to be encrypted. OpenSSLKey PKCS_8key = new BouncyCastleOpenSSLKey(kp.getPrivate()); long serial = 0; logger.debug( "createX509Cert Alg: " + algorithm + " bits:" + bits + " Issuer: " + issuer + " Subject: " + subject); logger.debug( "createX509Cert Sig alg:" + sigAlg + " Priv key format:" + PKCS_8key.getPrivateKey().getFormat()); // if ( pwd != null && ! PKCS_8key.isEncrypted()) // PKCS_8key.encrypt(pwd); // write private key PKCS_8key.writeTo(outPrivKey); // return X509 Cert return createX509V3Certificate( kp.getPublic(), kp.getPrivate(), months, issuer, subject, serial, sigAlg); }
@Override public void init(int key_size) throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(key_size, new SecureRandom()); KeyPair pair = keyGen.generateKeyPair(); PublicKey pubKey = pair.getPublic(); PrivateKey prvKey = pair.getPrivate(); d = ((RSAPrivateKey) prvKey).getPrivateExponent().toByteArray(); e = ((RSAPublicKey) pubKey).getPublicExponent().toByteArray(); n = ((RSAPrivateKey) prvKey).getModulus().toByteArray(); c = ((RSAPrivateCrtKey) prvKey).getCrtCoefficient().toByteArray(); ep = ((RSAPrivateCrtKey) prvKey).getPrimeExponentP().toByteArray(); eq = ((RSAPrivateCrtKey) prvKey).getPrimeExponentQ().toByteArray(); p = ((RSAPrivateCrtKey) prvKey).getPrimeP().toByteArray(); q = ((RSAPrivateCrtKey) prvKey).getPrimeQ().toByteArray(); }
/* * 产生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(); } }
private String getPubEncoded() { return Base64.getEncoder() .encodeToString(new X509EncodedKeySpec(pair.getPublic().getEncoded()).getEncoded()); }
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(); }
private SubjectPublicKeyInfo getSubjectPublicKeyInfo(KeyPair _keyPair) { byte[] encodedPublicKey = _keyPair.getPublic().getEncoded(); return new SubjectPublicKeyInfo(ASN1Sequence.getInstance(encodedPublicKey)); }
/** * Return the generated public value for this key agreement operation as a <code>BigInteger</code> * . * * @return The diffie-hellman public value as a <code>BigInteger</code>. */ public BigInteger getPublicValue() { DHPublicKey pubKey = (DHPublicKey) keyPair.getPublic(); return pubKey.getY(); }
public static void main(String[] args) { try { 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(); } }
public static void main(String[] args) throws NoSuchAlgorithmException { /* * STEP 1. * Alice creates public and private key. Bob receives her public key. */ final KeyPair keyPairAlice = KeyPairGenerator.getInstance("RSA").generateKeyPair(); final PublicKey pkAlice = keyPairAlice.getPublic(); final PrivateKey skAlice = keyPairAlice.getPrivate(); /* * STEP 2. * Setup an insecure communication channel. */ final BlockingQueue<byte[]> alice2bob = new LinkedBlockingQueue<>(); final BlockingQueue<byte[]> bob2alice = new LinkedBlockingQueue<>(); /* * STEP 3 Alice: * - uses private key to sign message. * - sends a 2-part message: * * message * * signature */ final Agent alice = new Agent("alice", bob2alice, alice2bob, skAlice, "SHA256withRSA") { @Override public void execute() throws Exception { /* * STEP 3.1 * Alice writes a message and sends to Bob. */ final String text = "I love you Bob. Kisses, Alice."; outgoing.put(text.getBytes("UTF-8")); /* * TODO STEP 3.2 * In addition, Alice signs message using selected * algorithm and her private key. */ } }; /* * STEP 4. Bob : * - receives a 2-part message: * * message * * Signature * - uses Alice's public key to verify message authenticity and integrity. */ final Agent bob = new Agent("bob", alice2bob, bob2alice, pkAlice, "SHA256withRSA") { @Override public void execute() throws Exception { /* * STEP 4.1 * Bob receives the message from Alice. */ final byte[] pt = incoming.take(); final String m = new String(pt, "UTF-8"); print("Received: %s (%s)", m, hex(pt)); /* * TODO STEP 4.2 * Bob setups signature verification. He has to provide * received text and Alice's public key. */ /* * TODO: STEP 4.3 * Bob verifies Alice's signature. */ } }; bob.start(); alice.start(); }
/** send client's public key to server and request server's public key */ private void sendKeyRequest() { Message newMsg = new Message(keyServerAddr, local_addr, Kpair.getPublic().getEncoded()) .putHeader(this.id, new EncryptHeader(EncryptHeader.KEY_REQUEST, getSymVersion())); down_prot.down(new Event(Event.MSG, newMsg)); }