Example #1
0
 public void setPubKey(byte[] y, byte[] p, byte[] q, byte[] g) throws Exception {
   DSAPublicKeySpec dsaPubKeySpec =
       new DSAPublicKeySpec(
           new BigInteger(y), new BigInteger(p), new BigInteger(q), new BigInteger(g));
   PublicKey pubKey = keyFactory.generatePublic(dsaPubKeySpec);
   signature.initVerify(pubKey);
 }
Example #2
0
  public SymmetricCryptor getSymmetricCryptor(
      byte[] peerPublicKeyBytes, boolean useSealedObject, ClassLoader classLoader)
      throws CryptoException {
    if (privateKey == null) {
      throw new IllegalStateException(
          "KeyGenerator did not successfully generate public key"); //$NON-NLS-1$
    }
    try {
      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(peerPublicKeyBytes);
      KeyFactory keyFact = KeyFactory.getInstance(ALGORITHM);
      PublicKey publicKey = keyFact.generatePublic(x509KeySpec);

      KeyAgreement ka = KeyAgreement.getInstance(ALGORITHM);
      ka.init(privateKey);
      ka.doPhase(publicKey, true);
      byte[] secret = ka.generateSecret();

      MessageDigest sha = MessageDigest.getInstance(DIGEST);
      byte[] hash = sha.digest(secret);
      byte[] symKey = new byte[keySize / 8];
      System.arraycopy(hash, 0, symKey, 0, symKey.length);
      SymmetricCryptor sc = SymmetricCryptor.getSymmectricCryptor(symKey);
      sc.setUseSealedObject(useSealedObject);
      sc.setClassLoader(classLoader);
      return sc;
    } catch (NoSuchAlgorithmException e) {
      throw new CryptoException(CorePlugin.Event.TEIID10003, e);
    } catch (InvalidKeySpecException e) {
      throw new CryptoException(CorePlugin.Event.TEIID10004, e);
    } catch (InvalidKeyException e) {
      throw new CryptoException(CorePlugin.Event.TEIID10005, e);
    }
  }
  public static VotifierKeyPair read(JsonObject source) throws Exception {
    byte[] publicKeyEnc = Base64.getDecoder().decode(source.get("public_key").getAsString());
    byte[] privateKeyEnc = Base64.getDecoder().decode(source.get("private_key").getAsString());

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyEnc));
    PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyEnc));

    return new VotifierKeyPair(new KeyPair(publicKey, privateKey));
  }
 private PublicKey getPublicKey(BigInteger pubExp, BigInteger modulus)
     throws InvalidKeySpecException {
   RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(modulus, pubExp);
   KeyFactory keyFactory = null;
   try {
     keyFactory = KeyFactory.getInstance("RSA");
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   }
   return keyFactory.generatePublic(pubSpec);
 }
Example #5
0
 /**
  * used to reconstitute public key sent in byte form from peer
  *
  * @param encodedKey
  * @return PublicKey
  */
 private PublicKey generatePubKey(byte[] encodedKey) {
   PublicKey pubKey = null;
   try {
     KeyFactory KeyFac = KeyFactory.getInstance(getAlgorithm(asymAlgorithm));
     X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(encodedKey);
     pubKey = KeyFac.generatePublic(x509KeySpec);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return pubKey;
 }
 /**
  * Complete the key agreement protocol with the peer public value <code>otherPublic</code> and
  * return the calculated shared secret.
  *
  * @param otherPublic The peer public value.
  * @return The shared secret value produced by the protocol.
  */
 public byte[] getSharedSecret(BigInteger otherPublic) {
   try {
     KeyFactory factory = KeyFactory.getInstance("DH");
     DHPublicKeySpec pub = new DHPublicKeySpec(otherPublic, P1024, G);
     PublicKey key = factory.generatePublic(pub);
     dh.doPhase(key, true);
     return dh.generateSecret();
   } catch (GeneralSecurityException e) {
     throw new TorException(e);
   }
 }
 public static PublicKey func_75896_a(byte p_75896_0_[]) {
   try {
     X509EncodedKeySpec x509encodedkeyspec = new X509EncodedKeySpec(p_75896_0_);
     KeyFactory keyfactory = KeyFactory.getInstance("RSA");
     return keyfactory.generatePublic(x509encodedkeyspec);
   } catch (NoSuchAlgorithmException nosuchalgorithmexception) {
     nosuchalgorithmexception.printStackTrace();
   } catch (InvalidKeySpecException invalidkeyspecexception) {
     invalidkeyspecexception.printStackTrace();
   }
   System.err.println("Public key reconstitute failed!");
   return null;
 }
Example #8
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 #9
0
 /**
  * Generates a PublicKey instance from a string containing the Base64-encoded public key.
  *
  * @param encodedPublicKey Base64-encoded public key
  * @throws IllegalArgumentException if encodedPublicKey is invalid
  */
 private PublicKey generatePublicKey(String encodedPublicKey) {
   try {
     byte[] decodedKey = Base64.decode(encodedPublicKey);
     KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
     return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
   } catch (NoSuchAlgorithmException e) {
     throw new RuntimeException(e);
   } catch (InvalidKeySpecException e) {
     Log.e(TAG, "Invalid key specification.");
     throw new IllegalArgumentException(e);
   } catch (Base64DecoderException e) {
     Log.e(TAG, "Base64 decoding failed.");
     throw new IllegalArgumentException(e);
   }
 }
Example #10
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;
  }
Example #11
0
 /**
  * Construct a public key from its encoding.
  *
  * @param encodedKey the encoding of a public key.
  * @param encodedKeyAlgorithm the algorithm the encodedKey is for.
  * @return a public key constructed from the encodedKey.
  */
 private static final PublicKey constructPublicKey(byte[] encodedKey, String encodedKeyAlgorithm)
     throws InvalidKeyException, NoSuchAlgorithmException {
   try {
     KeyFactory keyFactory = KeyFactory.getInstance(encodedKeyAlgorithm);
     X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey);
     return keyFactory.generatePublic(keySpec);
   } catch (NoSuchAlgorithmException nsae) {
     throw new NoSuchAlgorithmException(
         "No installed providers "
             + "can create keys for the "
             + encodedKeyAlgorithm
             + "algorithm",
         nsae);
   } catch (InvalidKeySpecException ike) {
     throw new InvalidKeyException("Cannot construct public key", ike);
   }
 }
Example #12
0
  private boolean checkSignature(String publicKey, String strToSign, byte[] sign) {
    try {
      KeyFactory keyFactory = KeyFactory.getInstance("RSA");
      byte[] encodedKey = Base64.decodeBase64(publicKey);
      PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
      java.security.Signature signature = java.security.Signature.getInstance("MD5withRSA");
      signature.initVerify(pubKey);
      signature.update(strToSign.getBytes());
      return signature.verify(sign);

    } catch (InvalidKeySpecException
        | NoSuchAlgorithmException
        | SignatureException
        | InvalidKeyException e) {
      log.error(e.getMessage());
    }
    return false;
  }
  /**
   * Converts byte array to an EC public key, by decoding the Q point parameter.
   *
   * @param keyBytes Bytes to be converted to EC public key.
   * @return An instance of the EC public key on success, or null on failure.
   * @throws InvalidKeySpecException When provided bytes are not a correct key representation.
   */
  @Override
  public PublicKey convertBytesToPublicKey(byte[] keyBytes) throws InvalidKeySpecException {
    try {
      KeyFactory kf = KeyFactory.getInstance("ECDH", getProviderName());

      ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256r1");
      if (ecSpec == null) { // can happen with incorrectly initialized crypto provider
        return null;
      }
      ECPoint point = ecSpec.getCurve().decodePoint(keyBytes);
      ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, ecSpec);

      ECPublicKey publicKey = (ECPublicKey) kf.generatePublic(pubSpec);
      return publicKey;
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
      Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    }
    return null;
  }
Example #14
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;
  }
 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 static PublicKey recreatePublicKey(String path) {
    FileInputStream file = null;
    RSAPublicKey key_public = null;
    try {
      file = new FileInputStream(path);
      ObjectInputStream obj_cle = new ObjectInputStream(file);
      BigInteger modulus = (BigInteger) obj_cle.readObject();
      BigInteger exponent = (BigInteger) obj_cle.readObject();
      RSAPublicKeySpec cle_reconst = new RSAPublicKeySpec(modulus, exponent);
      KeyFactory keyFactory = KeyFactory.getInstance("RSA");
      key_public = (RSAPublicKey) keyFactory.generatePublic(cle_reconst);

    } catch (Exception ex) {
      System.err.println("Probeleme de recreartion cle public: " + ex);
    } finally {
      try {
        file.close();
      } catch (Exception ex) {
        System.err.println("Probeleme de fermiture de fichier de la cle public: " + ex);
      }
    }
    return key_public;
  }
Example #17
0
  /*
   * 验证签名
   */
  public boolean verifySHA1withRSASigature(String sign, String src, String pubKey) {
    try {

      Signature sigEng = Signature.getInstance("SHA1withRSA");

      byte[] pubbyte = hexStrToBytes(pubKey.trim());

      X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubbyte);
      KeyFactory fac = KeyFactory.getInstance("RSA");
      RSAPublicKey publicKey = (RSAPublicKey) fac.generatePublic(keySpec);

      sigEng.initVerify(publicKey);
      sigEng.update(src.getBytes());

      byte[] sign1 = hexStrToBytes(sign);
      return sigEng.verify(sign1);

    } catch (Exception e) {
      System.err.println(e);
      e.printStackTrace(System.err);
      return false;
    }
  }
Example #18
0
 public void setPubKey(byte[] e, byte[] n) throws Exception {
   RSAPublicKeySpec rsaPubKeySpec = new RSAPublicKeySpec(new BigInteger(n), new BigInteger(e));
   PublicKey pubKey = keyFactory.generatePublic(rsaPubKeySpec);
   signature.initVerify(pubKey);
 }
  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 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);
 }