/**
   * 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;
  }
Example #3
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);
    }
  }
 /**
  * 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);
   }
 }
 /**
  * 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 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 PrivateKey getPrivateKey(BigInteger privExp, BigInteger modulus)
     throws InvalidKeySpecException {
   RSAPrivateKeySpec privSpec = new RSAPrivateKeySpec(modulus, privExp);
   KeyFactory keyFactory = null;
   try {
     keyFactory = KeyFactory.getInstance("RSA");
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   }
   return keyFactory.generatePrivate(privSpec);
 }
Example #8
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;
 }
 public static void savePublicKeyInFile(String path, PublicKey key) {
   try {
     KeyFactory fac = KeyFactory.getInstance("RSA");
     RSAPublicKeySpec RSAspec = fac.getKeySpec(key, RSAPublicKeySpec.class);
     FileOutputStream file3 = new FileOutputStream(path);
     ObjectOutputStream obj_stream = new ObjectOutputStream(file3);
     obj_stream.writeObject(RSAspec.getModulus());
     obj_stream.writeObject(RSAspec.getPublicExponent());
   } catch (Exception ex) {
     System.err.println("Probeleme de sauvegarde de la cle public dans un fichier: " + ex);
   }
 }
 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;
 }
  /**
   * Convert a byte array to an EC private key by decoding the D number parameter.
   *
   * @param keyBytes Bytes to be converted to the EC private key.
   * @return An instance of EC private key decoded from the input bytes.
   * @throws InvalidKeySpecException The provided key bytes are not a valid EC private key.
   */
  @Override
  public PrivateKey convertBytesToPrivateKey(byte[] keyBytes) throws InvalidKeySpecException {
    try {
      KeyFactory kf = KeyFactory.getInstance("ECDH", getProviderName());
      BigInteger keyInteger = new BigInteger(keyBytes);
      ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256r1");
      ECPrivateKeySpec pubSpec = new ECPrivateKeySpec(keyInteger, ecSpec);

      ECPrivateKey privateKey = (ECPrivateKey) kf.generatePrivate(pubSpec);
      return privateKey;
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
      Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    }
    return null;
  }
Example #12
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 #13
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 #14
0
 /**
  * Construct a private key from its encoding.
  *
  * @param encodedKey the encoding of a private key.
  * @param encodedKeyAlgorithm the algorithm the wrapped key is for.
  * @return a private key constructed from the encodedKey.
  */
 private static final PrivateKey constructPrivateKey(byte[] encodedKey, String encodedKeyAlgorithm)
     throws InvalidKeyException, NoSuchAlgorithmException {
   try {
     KeyFactory keyFactory = KeyFactory.getInstance(encodedKeyAlgorithm);
     PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
     return keyFactory.generatePrivate(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 private key", ike);
   }
 }
Example #15
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;
  }
  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;
  }
  /**
   * 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 #18
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 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));
  }
Example #21
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 #22
0
  /*
   * 产生签名
   */
  public String generateSHA1withRSASigature(String src, String priKey) {
    try {

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

      byte[] pribyte = hexStrToBytes(priKey.trim());

      PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte);

      KeyFactory fac = KeyFactory.getInstance("RSA");
      //            RSAPublicKey pubKey = (RSAPublicKey)fac.generatePublic(keySpec);
      RSAPrivateKey privateKey = (RSAPrivateKey) fac.generatePrivate(keySpec);
      sigEng.initSign(privateKey);
      sigEng.update(src.getBytes());

      byte[] signature = sigEng.sign();
      return bytesToHexStr(signature);
    } catch (Exception e) {
      System.err.println(e);
      e.printStackTrace(System.err);
      return null;
    }
  }
  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;
  }
  public void main(Provider p) throws Exception {

    /*
     * Use Solaris SPARC 11.2 or later to avoid an intermittent failure
     * when running SunPKCS11-Solaris (8044554)
     */
    if (p.getName().equals("SunPKCS11-Solaris")
        && System.getProperty("os.name").equals("SunOS")
        && System.getProperty("os.arch").equals("sparcv9")
        && System.getProperty("os.version").compareTo("5.11") <= 0
        && getDistro().compareTo("11.2") < 0) {

      System.out.println(
          "SunPKCS11-Solaris provider requires " + "Solaris SPARC 11.2 or later, skipping");
      return;
    }

    long start = System.currentTimeMillis();
    provider = p;
    data = new byte[2048];
    new Random().nextBytes(data);
    KeyStore ks = getKeyStore();
    KeyFactory kf = KeyFactory.getInstance("RSA", provider);
    for (Enumeration e = ks.aliases(); e.hasMoreElements(); ) {
      String alias = (String) e.nextElement();
      if (ks.isKeyEntry(alias)) {
        System.out.println("* Key " + alias + "...");
        PrivateKey privateKey = (PrivateKey) ks.getKey(alias, password);
        PublicKey publicKey = ks.getCertificate(alias).getPublicKey();
        privateKey = (PrivateKey) kf.translateKey(privateKey);
        publicKey = (PublicKey) kf.translateKey(publicKey);
        test(privateKey, publicKey);
      }
    }
    long stop = System.currentTimeMillis();
    System.out.println("All tests passed (" + (stop - start) + " ms).");
  }
Example #25
0
 public RSAPrivateKey decodePrivateKeyFromPKCSBytes(byte[] keySpecBytes)
     throws GeneralSecurityException {
   KeySpec keySpec = new PKCS8EncodedKeySpec(keySpecBytes);
   KeyFactory keyFact = KeyFactory.getInstance("RSA", PROVIDER_NAME);
   return (RSAPrivateKey) keyFact.generatePrivate(keySpec);
 }
 private RSAPublicKeySpec getPublicKeySpec(PublicKey publicKey)
     throws NoSuchAlgorithmException, InvalidKeySpecException {
   KeyFactory keyFac = KeyFactory.getInstance("RSA");
   return keyFac.getKeySpec(publicKey, RSAPublicKeySpec.class);
 }
  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 #28
0
 public void init() throws Exception {
   signature = java.security.Signature.getInstance("SHA1withRSA");
   keyFactory = KeyFactory.getInstance("RSA");
 }
 private static KeyFactory newKeyFactory() throws Exception {
   return KeyFactory.getInstance(KEY_ALGORITHM);
 }
Example #30
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;
  }