/**
   * 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);
    }
  }
Example #2
0
 public void setPrvKey(byte[] x, byte[] p, byte[] q, byte[] g) throws Exception {
   DSAPrivateKeySpec dsaPrivKeySpec =
       new DSAPrivateKeySpec(
           new BigInteger(x), new BigInteger(p), new BigInteger(q), new BigInteger(g));
   PrivateKey prvKey = keyFactory.generatePrivate(dsaPrivKeySpec);
   signature.initSign(prvKey);
 }
 /**
  * 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);
   }
 }
  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);
 }
  /**
   * 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 #7
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 #8
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;
    }
  }
Example #9
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);
 }
Example #10
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;
  }
  /*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);
  }
Example #12
0
 public void setPrvKey(byte[] d, byte[] n) throws Exception {
   RSAPrivateKeySpec rsaPrivKeySpec = new RSAPrivateKeySpec(new BigInteger(n), new BigInteger(d));
   PrivateKey prvKey = keyFactory.generatePrivate(rsaPrivKeySpec);
   signature.initSign(prvKey);
 }