/**
   * Created primary key using openssl.
   *
   * <p>openssl req -x509 -nodes -days 365 -newkey rsa:1024 -sha1 -subj
   * '/C=GB/ST=/L=Manchester/CN=www.example.com' -keyout myrsakey.pem -out /tmp/myrsacert.pem
   * openssl pkcs8 -in myrsakey.pem -topk8 -nocrypt -out myrsakey.pk8
   */
  private static PrivateKey getPrivateKey() {
    String str =
        "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMPQ5BCMxlUq2TYy\n"
            + "iRIoEUsz6HGTJhHuasS2nx1Se4Co3lxwxyubVdFj8AuhHNJSmJvjlpbTsGOjLZpr\n"
            + "HyDEDdJmf1Fensh1MhUnBZ4a7uLrZrKzFHHJdamX9pxapB89vLeHlCot9hVXdrZH\n"
            + "nNtg6FdmRKH/8gbs8iDyIayFvzYDAgMBAAECgYA+c9MpTBy9cQsR9BAvkEPjvkx2\n"
            + "XL4ZnfbDgpNA4Nuu7yzsQrPjPomiXMNkkiAFHH67yVxwAlgRjyuuQlgNNTpKvyQt\n"
            + "XcHxffnU0820VmE23M+L7jg2TlB3+rUnEDmDvCoyjlwGDR6lNb7t7Fgg2iR+iaov\n"
            + "0iVzz+l9w0slRlyGsQJBAPWXW2m3NmFgqfDxtw8fsKC2y8o17/cnPjozRGtWb8LQ\n"
            + "g3VCb8kbOFHOYNGazq3M7+wD1qILF2h/HecgK9eQrZ0CQQDMHXoJMfKKbrFrTKgE\n"
            + "zyggO1gtuT5OXYeFewMEb5AbDI2FfSc2YP7SHij8iQ2HdukBrbTmi6qxh3HmIR58\n"
            + "I/AfAkEA0Y9vr0tombsUB8cZv0v5OYoBZvCTbMANtzfb4AOHpiKqqbohDOevLQ7/\n"
            + "SpvgVCmVaDz2PptcRAyEBZ5MCssneQJAB2pmvaDH7Ambfod5bztLfOhLCtY5EkXJ\n"
            + "n6rZcDbRaHorRhdG7m3VtDKOUKZ2DF7glkQGV33phKukErVPUzlHBwJAScD9TqaG\n"
            + "wJ3juUsVtujV23SnH43iMggXT7m82STpPGam1hPfmqu2Z0niePFo927ogQ7H1EMJ\n"
            + "UHgqXmuvk2X/Ww==";

    try {
      KeyFactory fac = KeyFactory.getInstance("RSA");
      PKCS8EncodedKeySpec privKeySpec =
          new PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary(str));
      return fac.generatePrivate(privKeySpec);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  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;
  }
 /**
  * Converts a PEM-encoded PKCS#8 private key into an RSAPrivateKey instance useable with JCE
  *
  * @param privateKey private key in PKCS#8 format and PEM-encoded
  * @return RSAPrivateKey instance containing the key
  */
 private static RSAPrivateKey rsaPrivateKeyDecode(final String privateKey) {
   try {
     final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
     final KeySpec ks = new PKCS8EncodedKeySpec(Base64.decodePadded(privateKey));
     return (RSAPrivateKey) keyFactory.generatePrivate(ks);
   } catch (final Exception e) {
     throw new RuntimeException("Failed to decode built-in private key", e);
   }
 }
Esempio n. 4
0
  public PublicKey LoadPublicKey(String path, String algorithm)
      throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Read Public Key.
    File filePublicKey = new File(path + "public.key");
    FileInputStream fis = new FileInputStream(path + "public.key");
    byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
    fis.read(encodedPublicKey);
    fis.close();

    // Generate PublicKey.
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
    return publicKey;
  }
  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;
  }
 static {
   try {
     FileInputStream keyfis = new FileInputStream("src/com/ingenium/ash/publicIngenium");
     byte[] encKey = new byte[keyfis.available()];
     keyfis.read(encKey);
     keyfis.close();
     X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
     KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
     pubKey = keyFactory.generatePublic(pubKeySpec);
   } catch (InvalidKeySpecException ex) {
     Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null, ex);
   } catch (NoSuchAlgorithmException ex) {
     Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null, ex);
   } catch (NoSuchProviderException ex) {
     Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null, ex);
   } catch (FileNotFoundException ex) {
     Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null, ex);
   } catch (IOException ex) {
     Logger.getLogger(SignatureVerifier.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
  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();
  }
Esempio n. 9
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);
 }
Esempio n. 11
0
 public void init() throws Exception {
   signature = java.security.Signature.getInstance("SHA1withRSA");
   keyFactory = KeyFactory.getInstance("RSA");
 }