public byte[] new_decrypt_cn(E_CODE paramE_CODE, byte[] paramArrayOfByte)
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
          InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    byte[] localObject = null;

    if (paramE_CODE == E_CODE.RSA) {
      if (rsa_key.length() > 2) {
        Cipher localCipher;
        byte[] arrayOfByte = new byte[0];
        //		    PublicKey localPublicKey = KeyFactory.getInstance("RSA").generatePublic(new
        // X509EncodedKeySpec(Base64.decodeBase64(rsa_key)));
        PublicKey localPublicKey =
            KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(Base64.decode(rsa_key, Base64.DEFAULT)));
        System.out.println("key  length-" + (Base64.decode(rsa_key, Base64.DEFAULT)).length);
        System.out.println("data length-" + paramArrayOfByte.length);
        localCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        localCipher.init(Cipher.DECRYPT_MODE, localPublicKey);
        //		    localCipher.init(Cipher.ENCRYPT_MODE, localPublicKey);

        arrayOfByte = localCipher.doFinal(paramArrayOfByte);
        //		    int oldLength;
        //		    for (int i = 0; i < paramArrayOfByte.length; i += 8) {
        //		        byte[] temp = localCipher.doFinal(paramArrayOfByte, i, i + 8);
        //		        oldLength = arrayOfByte.length;
        //		        arrayOfByte  = Arrays.copyOf(arrayOfByte, temp.length+arrayOfByte.length);
        //		        System.arraycopy(temp, 0, arrayOfByte, oldLength, temp.length);
        //		    }

        //		    arrayOfByte = paramArrayOfByte;

        return arrayOfByte;
      }
    } else if (paramE_CODE == E_CODE.RSA_EP) {
      if (rsa_ep_key.length() >= 2) {
        //        PrivateKey localPrivateKey = KeyFactory.getInstance("RSA").generatePrivate(new
        // PKCS8EncodedKeySpec(Base64.decodeBase64(rsa_ep_key)));
        PrivateKey localPrivateKey =
            KeyFactory.getInstance("RSA")
                .generatePrivate(
                    new PKCS8EncodedKeySpec(Base64.decode(rsa_ep_key, Base64.DEFAULT)));
        Cipher localCipher2 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        localCipher2.init(2, localPrivateKey);
        localObject = localCipher2.doFinal(paramArrayOfByte);
      }
    } else if (paramE_CODE == E_CODE.AES) {
      //      SecretKeySpec localSecretKeySpec = new
      // SecretKeySpec(Base64.decodeBase64(aes_key.getBytes()), "AES");
      //      byte[] arrayOfByte1 = Base64.decodeBase64(paramArrayOfByte);
      SecretKeySpec localSecretKeySpec =
          new SecretKeySpec(Base64.decode(aes_key.getBytes(), Base64.DEFAULT), "AES");
      byte[] arrayOfByte1 = Base64.decode(paramArrayOfByte, Base64.DEFAULT);
      Cipher localCipher1 = Cipher.getInstance("AES/ECB/PKCS5Padding");
      localCipher1.init(Cipher.DECRYPT_MODE, localSecretKeySpec);
      byte[] arrayOfByte2 = localCipher1.doFinal(arrayOfByte1);
      localObject = arrayOfByte2;
    }

    return localObject;
  }
Example #2
0
 /**
  * Get the secret data that has been agreed on through Diffie-Hellman key agreement protocol. Note
  * that in the two party protocol, if the peer keys are already known, no other data needs to be
  * sent in order to agree on a secret. That is, a secured message may be sent without any
  * mandatory round-trip overheads.
  *
  * <p>It is illegal to call this member function if the private key has not been set (or
  * generated).
  *
  * @param peerPublicKey the peer's public key.
  * @returns the secret, which is an unsigned big-endian integer the same size as the
  *     Diffie-Hellman modulus.
  */
 SecretKey getAgreedSecret(BigInteger peerPublicValue) {
   try {
     KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
     DHPublicKeySpec spec = new DHPublicKeySpec(peerPublicValue, modulus, base);
     PublicKey publicKey = kf.generatePublic(spec);
     KeyAgreement ka = JsseJce.getKeyAgreement("DiffieHellman");
     ka.init(privateKey);
     ka.doPhase(publicKey, true);
     return ka.generateSecret("TlsPremasterSecret");
   } catch (GeneralSecurityException e) {
     throw new RuntimeException("Could not generate secret", e);
   }
 }
Example #3
0
 static DHPublicKeySpec getDHPublicKeySpec(PublicKey key) {
   if (key instanceof DHPublicKey) {
     DHPublicKey dhKey = (DHPublicKey) key;
     DHParameterSpec params = dhKey.getParams();
     return new DHPublicKeySpec(dhKey.getY(), params.getP(), params.getG());
   }
   try {
     KeyFactory factory = JsseJce.getKeyFactory("DH");
     return (DHPublicKeySpec) factory.getKeySpec(key, DHPublicKeySpec.class);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Example #4
0
  public byte[] getK() throws Exception {
    if (K == null) {
      KeyFactory myKeyFac = KeyFactory.getInstance("DH");
      DHPublicKeySpec keySpec = new DHPublicKeySpec(f, p, g);
      PublicKey yourPubKey = myKeyFac.generatePublic(keySpec);

      myKeyAgree.doPhase(yourPubKey, true);
      byte[] mySharedSecret = myKeyAgree.generateSecret();

      K = new BigInteger(mySharedSecret);
      K_array = K.toByteArray();

      // System.err.println("K.signum(): "+K.signum()+
      // " "+Integer.toHexString(mySharedSecret[0]&0xff)+
      // " "+Integer.toHexString(K_array[0]&0xff));

      K_array = mySharedSecret;
    }
    return K_array;
  }
  public byte[] new_encrypt_cn(E_CODE paramE_CODE, String val) {
    byte[] localObject = null;
    try {
      if (paramE_CODE == E_CODE.RSA) {
        /*if (rsa_key.length() > 2)
        {
            Cipher localCipher;
            byte[] arrayOfByte = null;
            PublicKey localPublicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.decodeBase64(rsa_key)));
            localCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            localCipher.init(Cipher.ENCRYPT_MODE, localPublicKey);
            arrayOfByte = localCipher.doFinal(val.getBytes());
            return arrayOfByte;
        }*/
        return null;
      } else if (paramE_CODE == E_CODE.RSA_EP) {
        if (rsa_key.length() >= 2) {
          Cipher localCipher;
          PublicKey localPublicKey;

          //  		byte[] b = Base64.decodeBase64(rsa_key);
          byte[] b = Base64.decode(rsa_key, Base64.DEFAULT);
          X509EncodedKeySpec sp = new X509EncodedKeySpec(b);
          localPublicKey = KeyFactory.getInstance("RSA").generatePublic(sp);
          localCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
          localCipher.init(Cipher.ENCRYPT_MODE, localPublicKey);
          localObject = localCipher.doFinal(val.getBytes("utf-8"));
        }
      } else if (paramE_CODE == E_CODE.AES) {
        //    SecretKeySpec localSecretKeySpec = new
        // SecretKeySpec(Base64.decodeBase64(aes_key.getBytes()), "AES");
        SecretKeySpec localSecretKeySpec =
            new SecretKeySpec(Base64.decode(aes_key.getBytes(), Base64.DEFAULT), "AES");
        Cipher localCipher1 = Cipher.getInstance("AES/ECB/PKCS5Padding");
        localCipher1.init(Cipher.ENCRYPT_MODE, localSecretKeySpec);
        localObject = localCipher1.doFinal(val.getBytes());
        //       = arrayOfByte2;
      }
    } catch (Exception localException) {
      System.out.println("new _e_cn-" + localException);
      return null;
    }
    return localObject;
  }
  public String get_K() {
    if (rsa_key.length() < 2) return null;
    Cipher localCipher;
    byte[] arrayOfByte = null;

    PublicKey localPublicKey;
    try {
      //		byte[] b = Base64.decode(rsa_key);
      byte[] b = Base64.decode(rsa_key, Base64.DEFAULT);
      X509EncodedKeySpec sp = new X509EncodedKeySpec(b);
      localPublicKey = KeyFactory.getInstance("RSA").generatePublic(sp);
      localCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
      localCipher.init(Cipher.ENCRYPT_MODE, localPublicKey);
      arrayOfByte = localCipher.doFinal(aes_key.getBytes("utf-8"));
    } catch (Exception e) {
      // e.printStackTrace();
      return null;
    }
    //	return new String(Base64.encode(arrayOfByte));
    return new String(Base64.encode(arrayOfByte, Base64.DEFAULT));
  }
  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();
  }
Example #8
0
  /**
   * Returns the key associated with the given alias, using the given password to recover it.
   *
   * @param alias the alias name
   * @param password the password for recovering the key. This password is used internally as the
   *     key is exported in a PKCS12 format.
   * @return the requested key, or null if the given alias does not exist or does not identify a
   *     <i>key entry</i>.
   * @exception NoSuchAlgorithmException if the algorithm for recovering the key cannot be found
   * @exception UnrecoverableKeyException if the key cannot be recovered (e.g., the given password
   *     is wrong).
   */
  public Key engineGetKey(String alias, char[] password)
      throws NoSuchAlgorithmException, UnrecoverableKeyException {
    permissionCheck();

    // An empty password is rejected by MacOS API, no private key data
    // is exported. If no password is passed (as is the case when
    // this implementation is used as browser keystore in various
    // deployment scenarios like Webstart, JFX and applets), create
    // a dummy password so MacOS API is happy.
    if (password == null || password.length == 0) {
      // Must not be a char array with only a 0, as this is an empty
      // string.
      if (random == null) {
        random = new SecureRandom();
      }
      password = Long.toString(random.nextLong()).toCharArray();
    }

    Object entry = entries.get(alias.toLowerCase());

    if (entry == null || !(entry instanceof KeyEntry)) {
      return null;
    }

    // This call gives us a PKCS12 bag, with the key inside it.
    byte[] exportedKeyInfo = _getEncodedKeyData(((KeyEntry) entry).keyRef, password);
    if (exportedKeyInfo == null) {
      return null;
    }

    PrivateKey returnValue = null;

    try {
      byte[] pkcs8KeyData = fetchPrivateKeyFromBag(exportedKeyInfo);
      byte[] encryptedKey;
      AlgorithmParameters algParams;
      ObjectIdentifier algOid;
      try {
        // get the encrypted private key
        EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(pkcs8KeyData);
        encryptedKey = encrInfo.getEncryptedData();

        // parse Algorithm parameters
        DerValue val = new DerValue(encrInfo.getAlgorithm().encode());
        DerInputStream in = val.toDerInputStream();
        algOid = in.getOID();
        algParams = parseAlgParameters(in);

      } catch (IOException ioe) {
        UnrecoverableKeyException uke =
            new UnrecoverableKeyException(
                "Private key not stored as " + "PKCS#8 EncryptedPrivateKeyInfo: " + ioe);
        uke.initCause(ioe);
        throw uke;
      }

      // Use JCE to decrypt the data using the supplied password.
      SecretKey skey = getPBEKey(password);
      Cipher cipher = Cipher.getInstance(algOid.toString());
      cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
      byte[] decryptedPrivateKey = cipher.doFinal(encryptedKey);
      PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(decryptedPrivateKey);

      // Parse the key algorithm and then use a JCA key factory to create the private key.
      DerValue val = new DerValue(decryptedPrivateKey);
      DerInputStream in = val.toDerInputStream();

      // Ignore this -- version should be 0.
      int i = in.getInteger();

      // Get the Algorithm ID next
      DerValue[] value = in.getSequence(2);
      AlgorithmId algId = new AlgorithmId(value[0].getOID());
      String algName = algId.getName();

      // Get a key factory for this algorithm.  It's likely to be 'RSA'.
      KeyFactory kfac = KeyFactory.getInstance(algName);
      returnValue = kfac.generatePrivate(kspec);
    } catch (Exception e) {
      UnrecoverableKeyException uke =
          new UnrecoverableKeyException("Get Key failed: " + e.getMessage());
      uke.initCause(e);
      throw uke;
    }

    return returnValue;
  }
 private static KeyFactory newKeyFactory() throws Exception {
   return KeyFactory.getInstance(KEY_ALGORITHM);
 }
 /*
 public static PublicKey readPublicKey(String filenameDer) throws Exception
 {
   byte[] keyBytes = readAllBytes(filenameDer);
   return readPublicKey(keyBytes);
 }*/
 public static PublicKey readPublicKey(byte[] keyBytes) throws Exception {
   KeyFactory keyFactory = newKeyFactory();
   X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
   return keyFactory.generatePublic(spec);
 }
  /*public static PrivateKey readPrivateKey(String filenameDer) throws Exception
  {
      byte[] keyBytes = readAllBytes(filenameDer);
    logger.debug("Key = " +  Hex.encodeHexString(keyBytes));
    return readPrivateKey(keyBytes);
  }*/
  public static PrivateKey readPrivateKey(byte[] keyBytes) throws Exception {

    KeyFactory keyFactory = newKeyFactory();
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    return keyFactory.generatePrivate(spec);
  }