コード例 #1
1
  /**
   * 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);
    }
  }
コード例 #2
0
  private void testKeyFactory() throws Exception {
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "SC");

    ECCurve curve =
        new ECCurve.Fp(
            new BigInteger(
                "883423532389192164791648750360308885314476597252960362792450860609699839"), // q
            new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
            new BigInteger(
                "6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b

    ECParameterSpec ecSpec =
        new ECParameterSpec(
            curve,
            curve.decodePoint(
                Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
            new BigInteger(
                "883423532389192164791648750360308884807550341691627752275345424702807307")); // n

    ConfigurableProvider config = (ConfigurableProvider) Security.getProvider("SC");

    config.setParameter(ConfigurableProvider.EC_IMPLICITLY_CA, ecSpec);

    g.initialize(null, new SecureRandom());

    KeyPair p = g.generateKeyPair();

    ECPrivateKey sKey = (ECPrivateKey) p.getPrivate();
    ECPublicKey vKey = (ECPublicKey) p.getPublic();

    KeyFactory fact = KeyFactory.getInstance("ECDSA", "SC");

    vKey = (ECPublicKey) fact.generatePublic(new ECPublicKeySpec(vKey.getQ(), null));
    sKey = (ECPrivateKey) fact.generatePrivate(new ECPrivateKeySpec(sKey.getD(), null));

    testECDSA(sKey, vKey);

    testBCParamsAndQ(sKey, vKey);
    testEC5Params(sKey, vKey);

    testEncoding(sKey, vKey);

    ECPublicKey vKey2 = (ECPublicKey) fact.generatePublic(new ECPublicKeySpec(vKey.getQ(), ecSpec));
    ECPrivateKey sKey2 =
        (ECPrivateKey) fact.generatePrivate(new ECPrivateKeySpec(sKey.getD(), ecSpec));

    if (!vKey.equals(vKey2) || vKey.hashCode() != vKey2.hashCode()) {
      fail("private equals/hashCode failed");
    }

    if (!sKey.equals(sKey2) || sKey.hashCode() != sKey2.hashCode()) {
      fail("private equals/hashCode failed");
    }

    // check we can get specs.
    fact.getKeySpec(vKey, java.security.spec.ECPublicKeySpec.class);

    fact.getKeySpec(sKey, java.security.spec.ECPrivateKeySpec.class);
  }
コード例 #3
0
  public PrivateKey getPrivateKey(PGPPrivateKey privKey) throws PGPException {
    PublicKeyPacket pubPk = privKey.getPublicKeyPacket();
    BCPGKey privPk = privKey.getPrivateKeyDataPacket();

    try {
      KeyFactory fact;

      switch (pubPk.getAlgorithm()) {
        case PGPPublicKey.RSA_ENCRYPT:
        case PGPPublicKey.RSA_GENERAL:
        case PGPPublicKey.RSA_SIGN:
          RSAPublicBCPGKey rsaPub = (RSAPublicBCPGKey) pubPk.getKey();
          RSASecretBCPGKey rsaPriv = (RSASecretBCPGKey) privPk;
          RSAPrivateCrtKeySpec rsaPrivSpec =
              new RSAPrivateCrtKeySpec(
                  rsaPriv.getModulus(),
                  rsaPub.getPublicExponent(),
                  rsaPriv.getPrivateExponent(),
                  rsaPriv.getPrimeP(),
                  rsaPriv.getPrimeQ(),
                  rsaPriv.getPrimeExponentP(),
                  rsaPriv.getPrimeExponentQ(),
                  rsaPriv.getCrtCoefficient());

          fact = helper.createKeyFactory("RSA");

          return fact.generatePrivate(rsaPrivSpec);
        case PGPPublicKey.DSA:
          DSAPublicBCPGKey dsaPub = (DSAPublicBCPGKey) pubPk.getKey();
          DSASecretBCPGKey dsaPriv = (DSASecretBCPGKey) privPk;
          DSAPrivateKeySpec dsaPrivSpec =
              new DSAPrivateKeySpec(dsaPriv.getX(), dsaPub.getP(), dsaPub.getQ(), dsaPub.getG());

          fact = helper.createKeyFactory("DSA");

          return fact.generatePrivate(dsaPrivSpec);
        case PGPPublicKey.ELGAMAL_ENCRYPT:
        case PGPPublicKey.ELGAMAL_GENERAL:
          ElGamalPublicBCPGKey elPub = (ElGamalPublicBCPGKey) pubPk.getKey();
          ElGamalSecretBCPGKey elPriv = (ElGamalSecretBCPGKey) privPk;
          ElGamalPrivateKeySpec elSpec =
              new ElGamalPrivateKeySpec(
                  elPriv.getX(), new ElGamalParameterSpec(elPub.getP(), elPub.getG()));

          fact = helper.createKeyFactory("ElGamal");

          return fact.generatePrivate(elSpec);
        default:
          throw new PGPException("unknown public key algorithm encountered");
      }
    } catch (PGPException e) {
      throw e;
    } catch (Exception e) {
      throw new PGPException("Exception constructing key", e);
    }
  }
コード例 #4
0
ファイル: TestKeyFactory.java プロジェクト: netroby/jdk9-dev
 private static void testPrivate(KeyFactory kf, PrivateKey key) throws Exception {
   System.out.println("Testing private key...");
   PrivateKey key2 = (PrivateKey) kf.translateKey(key);
   KeySpec keySpec = kf.getKeySpec(key, ECPrivateKeySpec.class);
   PrivateKey key3 = kf.generatePrivate(keySpec);
   KeySpec pkcs8Spec = kf.getKeySpec(key, PKCS8EncodedKeySpec.class);
   PrivateKey key4 = kf.generatePrivate(pkcs8Spec);
   KeySpec pkcs8Spec2 = new PKCS8EncodedKeySpec(key.getEncoded());
   PrivateKey key5 = kf.generatePrivate(pkcs8Spec2);
   testKey(key, key);
   testKey(key, key2);
   testKey(key, key3);
   testKey(key, key4);
   testKey(key, key5);
 }
コード例 #5
0
ファイル: CommonSign.java プロジェクト: lzs0420/mytest
 @Override
 protected Key initDecryptKey() throws Exception {
   KeyFactory mykeyFactory = KeyFactory.getInstance(getAlgorithm());
   PKCS8EncodedKeySpec priv_spec = new PKCS8EncodedKeySpec(getDecryptKey());
   PrivateKey privKey = mykeyFactory.generatePrivate(priv_spec);
   return privKey;
 }
コード例 #6
0
 private KeyPair loadKey(final JSONObject keys) {
   if (keys == null) {
     return null;
   }
   synchronized (keys) {
     try {
       BigInteger x = new BigInteger(keys.getString("otr_x"), 16);
       BigInteger y = new BigInteger(keys.getString("otr_y"), 16);
       BigInteger p = new BigInteger(keys.getString("otr_p"), 16);
       BigInteger q = new BigInteger(keys.getString("otr_q"), 16);
       BigInteger g = new BigInteger(keys.getString("otr_g"), 16);
       KeyFactory keyFactory = KeyFactory.getInstance("DSA");
       DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(y, p, q, g);
       DSAPrivateKeySpec privateKeySpec = new DSAPrivateKeySpec(x, p, q, g);
       PublicKey publicKey = keyFactory.generatePublic(pubKeySpec);
       PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
       return new KeyPair(publicKey, privateKey);
     } catch (JSONException e) {
       return null;
     } catch (NoSuchAlgorithmException e) {
       return null;
     } catch (InvalidKeySpecException e) {
       return null;
     }
   }
 }
コード例 #7
0
ファイル: SignatureDSA.java プロジェクト: savitrig/teledroid
 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);
 }
コード例 #8
0
ファイル: SSLUtil.java プロジェクト: opencadc/core
 public static PrivateKey readPrivateKey(byte[] bytesPrivateKey)
     throws InvalidKeySpecException, NoSuchAlgorithmException, IOException {
   KeyFactory kf = KeyFactory.getInstance("RSA");
   PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytesPrivateKey);
   PrivateKey pk = kf.generatePrivate(spec);
   return pk;
 }
コード例 #9
0
ファイル: RSAUtils.java プロジェクト: whg333/iTool
 /**
  * 通过私钥byte[]将公钥还原,适用于RSA算法
  *
  * @param keyBytes
  * @return
  * @throws NoSuchAlgorithmException
  * @throws InvalidKeySpecException
  */
 public static PrivateKey getPrivateKey(byte[] keyBytes)
     throws NoSuchAlgorithmException, InvalidKeySpecException {
   PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
   KeyFactory keyFactory = KeyFactory.getInstance(RSA);
   PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
   return privateKey;
 }
コード例 #10
0
  @Kroll.method
  public String decode(HashMap args) {
    // decode string back to plain text
    //
    KrollDict arg = new KrollDict(args);
    String txt = arg.getString("cipherText");
    byte[] bytesEncoded = Base64.decode(txt, 0);
    String keyString = arg.getString("privateKey");
    PrivateKey key;

    try {
      byte[] encodedKey = Base64.decode(keyString, 0);
      PKCS8EncodedKeySpec x509KeySpec = new PKCS8EncodedKeySpec(encodedKey);
      KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC");
      key = keyFact.generatePrivate(x509KeySpec);
    } catch (Exception e) {
      return "error key";
    }

    byte[] decodedBytes = null;

    try {
      Cipher c = Cipher.getInstance("RSA");
      c.init(Cipher.DECRYPT_MODE, key);
      decodedBytes = c.doFinal(bytesEncoded);
    } catch (Exception e) {
      Log.e(TAG, "RSA decryption error " + e.toString());
      return "error";
    }
    return new String(decodedBytes);
  }
コード例 #11
0
ファイル: RSAUtils.java プロジェクト: myicewater/book-wx
 /**
  * 私钥加密
  *
  * @param data 源数据
  * @param privateKey 私钥(BASE64编码)
  * @return
  * @throws Exception
  */
 public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
   byte[] keyBytes = Base64.decode(privateKey);
   PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
   KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
   Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
   Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
   cipher.init(Cipher.ENCRYPT_MODE, privateK);
   int inputLen = data.length;
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   int offSet = 0;
   byte[] cache;
   int i = 0;
   // 对数据分段加密
   while (inputLen - offSet > 0) {
     if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
       cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
     } else {
       cache = cipher.doFinal(data, offSet, inputLen - offSet);
     }
     out.write(cache, 0, cache.length);
     i++;
     offSet = i * MAX_ENCRYPT_BLOCK;
   }
   byte[] encryptedData = out.toByteArray();
   out.close();
   return encryptedData;
 }
コード例 #12
0
    private static Cipher createCipher(int mode, boolean isPrivate, byte[] key)
        throws InvalidKeyException, InvalidAlgorithmParameterException {
      try {
        KeyFactory factory =
            KeyFactory.getInstance(Configuration.DEFAULT_ASYMMETRIC_CIPHER_ALGORITHM);

        Key keyspec;
        if (isPrivate) {
          keyspec = factory.generatePrivate(new PKCS8EncodedKeySpec(key));
        } else {
          keyspec = factory.generatePublic(new X509EncodedKeySpec(key));
        }

        Cipher cipher = Cipher.getInstance(Configuration.DEFAULT_ASYMMETRIC_CIPHER);
        cipher.init(mode, keyspec);

        return cipher;
      } catch (InvalidKeySpecException e) {
        throw new IllegalConfigurationException(e);
      } catch (NoSuchAlgorithmException e) {
        throw new IllegalConfigurationException(e);
      } catch (NoSuchPaddingException e) {
        throw new IllegalConfigurationException(e);
      }
    }
コード例 #13
0
  /** Convert a PKCS#8 encoded private key into a PrivateKey object. */
  public PrivateKey convertEncodedPrivateKey(byte[] key, int algorithm) {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(key);
    DnsKeyAlgorithm algs = DnsKeyAlgorithm.getInstance();

    try {
      switch (algs.baseType(algorithm)) {
        case DnsKeyAlgorithm.RSA:
          return mRSAKeyFactory.generatePrivate(spec);
        case DnsKeyAlgorithm.DSA:
          return mDSAKeyFactory.generatePrivate(spec);
      }
    } catch (GeneralSecurityException e) {
    }

    return null;
  }
コード例 #14
0
 /**
  * Generates Private Key from BASE64 encoded string
  *
  * @param key BASE64 encoded string which represents the key
  * @return The PrivateKey
  * @throws java.lang.Exception
  */
 public static PrivateKey getPrivateKeyFromString(String key) throws Exception {
   KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
   BASE64Decoder b64 = new BASE64Decoder();
   EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(b64.decodeBuffer(key));
   PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
   return privateKey;
 }
コード例 #15
0
  public void addNewKey(String alias, Iterator<FileItem> uploadedFilesIterator) throws Exception {
    PrivateKey privateKey = null;
    Certificate[] certs = null;
    while (uploadedFilesIterator.hasNext()) {
      FileItem fileItem = uploadedFilesIterator.next();
      if (!fileItem.isFormField()) {
        if ("keyFile".equals(fileItem.getFieldName())) {
          KeyFactory kf = KeyFactory.getInstance("RSA");
          privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(fileItem.get()));
        }
        if ("certFile".equals(fileItem.getFieldName())) {
          CertificateFactory cf = CertificateFactory.getInstance("X.509");
          certs = cf.generateCertificates(fileItem.getInputStream()).toArray(new Certificate[] {});
        }
      }
    }

    if (privateKey == null || certs == null) {
      throw new WebApplicationException(
          Response.ok("<pre>Can't find input file.</pre>", MediaType.TEXT_HTML).build());
    }

    keystore.setKeyEntry(alias, privateKey, keyStorePassword.toCharArray(), certs);
    save();
  }
コード例 #16
0
ファイル: BankCoder.java プロジェクト: haiwi-song/Java
 /**
  * 生成RSA私钥
  *
  * @param privateKeyStr
  * @return
  * @throws Exception
  */
 public PrivateKey generateRSAPrivateKey(String privateKeyStr) throws Exception {
   KeyFactory keyFactory = KeyFactory.getInstance("RSA");
   EncodedKeySpec privateKeySpec =
       new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(privateKeyStr));
   RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec);
   return privateKey;
 }
コード例 #17
0
  protected Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType)
      throws InvalidKeyException {
    byte[] encoded = null;
    try {
      encoded = engineDoFinal(wrappedKey, 0, wrappedKey.length);
    } catch (BadPaddingException e) {
      throw new InvalidKeyException(e.getMessage());
    } catch (IllegalBlockSizeException e2) {
      throw new InvalidKeyException(e2.getMessage());
    }

    if (wrappedKeyType == Cipher.SECRET_KEY) {
      return new SecretKeySpec(encoded, wrappedKeyAlgorithm);
    } else {
      try {
        KeyFactory kf =
            KeyFactory.getInstance(wrappedKeyAlgorithm, BouncyCastleProvider.PROVIDER_NAME);

        if (wrappedKeyType == Cipher.PUBLIC_KEY) {
          return kf.generatePublic(new X509EncodedKeySpec(encoded));
        } else if (wrappedKeyType == Cipher.PRIVATE_KEY) {
          return kf.generatePrivate(new PKCS8EncodedKeySpec(encoded));
        }
      } catch (NoSuchProviderException e) {
        throw new InvalidKeyException("Unknown key type " + e.getMessage());
      } catch (NoSuchAlgorithmException e) {
        throw new InvalidKeyException("Unknown key type " + e.getMessage());
      } catch (InvalidKeySpecException e2) {
        throw new InvalidKeyException("Unknown key type " + e2.getMessage());
      }

      throw new InvalidKeyException("Unknown key type " + wrappedKeyType);
    }
  }
コード例 #18
0
ファイル: RSAUtil.java プロジェクト: pradp/yspro
  /**
   * 生成私钥
   *
   * @param modulus
   * @param privateExponent
   * @return RSAPrivateKey
   * @throws Exception
   */
  public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent)
      throws Exception {

    KeyFactory keyFac = null;

    try {

      keyFac =
          KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());

    } catch (NoSuchAlgorithmException ex) {

      throw new Exception(ex.getMessage());
    }

    RSAPrivateKeySpec priKeySpec =
        new RSAPrivateKeySpec(new BigInteger(modulus), new BigInteger(privateExponent));

    try {

      return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);

    } catch (InvalidKeySpecException ex) {

      throw new Exception(ex.getMessage());
    }
  }
コード例 #19
0
  /**
   * Returns the key pair (private and public key) for the local machine
   *
   * @param sessionID sessionID for currect machine
   */
  public KeyPair loadLocalKeyPair(SessionID sessionID) {
    if (sessionID == null) return null;

    String accountID = sessionID.getAccountID();
    // Load Private Key.
    byte[] b64PrivKey = this.store.getPropertyBytes(accountID + ".privateKey");
    if (b64PrivKey == null) return null;

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(b64PrivKey);

    // Load Public Key.
    byte[] b64PubKey = this.store.getPropertyBytes(accountID + ".publicKey");
    if (b64PubKey == null) return null;

    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(b64PubKey);

    PublicKey publicKey;
    PrivateKey privateKey;

    // Generate KeyPair.
    KeyFactory keyFactory;
    try {
      keyFactory = KeyFactory.getInstance("DSA");
      publicKey = keyFactory.generatePublic(publicKeySpec);
      privateKey = keyFactory.generatePrivate(privateKeySpec);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      return null;
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
      return null;
    }

    return new KeyPair(publicKey, privateKey);
  }
コード例 #20
0
  private KeyPair loadLocalKeyPair(String fullUserId) {
    PublicKey publicKey;
    PrivateKey privateKey;

    String userId = Address.stripResource(fullUserId);

    try {
      // Load Private Key.

      byte[] b64PrivKey = this.store.getPropertyBytes(userId + ".privateKey");
      if (b64PrivKey == null) return null;

      PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(b64PrivKey);

      // Generate KeyPair.
      KeyFactory keyFactory;
      keyFactory = KeyFactory.getInstance(KEY_ALG);
      privateKey = keyFactory.generatePrivate(privateKeySpec);

      // Load Public Key.
      byte[] b64PubKey = this.store.getPropertyBytes(userId + ".publicKey");
      if (b64PubKey == null) return null;

      X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(b64PubKey);
      publicKey = keyFactory.generatePublic(publicKeySpec);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      return null;
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
      return null;
    }

    return new KeyPair(publicKey, privateKey);
  }
コード例 #21
0
ファイル: RSA.java プロジェクト: Hammad31/SecureChatApp
  public static KeyPair LoadKeyPair(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();

    // Read Private Key.
    File filePrivateKey = new File(path + "/private.key");
    fis = new FileInputStream(path + "/private.key");
    byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
    fis.read(encodedPrivateKey);
    fis.close();

    // Generate KeyPair.
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return new KeyPair(publicKey, privateKey);
  }
コード例 #22
0
  private static PrivateKey derivePrivateKeyPBES2(
      org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn,
      AlgorithmIdentifier algId,
      char[] password)
      throws GeneralSecurityException, InvalidCipherTextException {
    PBES2Parameters pbeParams = new PBES2Parameters((ASN1Sequence) algId.getParameters());
    CipherParameters cipherParams = extractPBES2CipherParams(password, pbeParams);

    EncryptionScheme scheme = pbeParams.getEncryptionScheme();
    BufferedBlockCipher cipher;
    if (scheme.getAlgorithm().equals(PKCSObjectIdentifiers.RC2_CBC)) {
      RC2CBCParameter rc2Params = new RC2CBCParameter((ASN1Sequence) scheme.getObject());
      byte[] iv = rc2Params.getIV();
      CipherParameters param = new ParametersWithIV(cipherParams, iv);
      cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new RC2Engine()));
      cipher.init(false, param);
    } else {
      byte[] iv = ((ASN1OctetString) scheme.getObject()).getOctets();
      CipherParameters param = new ParametersWithIV(cipherParams, iv);
      cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()));
      cipher.init(false, param);
    }

    byte[] data = eIn.getEncryptedData();
    byte[] out = new byte[cipher.getOutputSize(data.length)];
    int len = cipher.processBytes(data, 0, data.length, out, 0);
    len += cipher.doFinal(out, len);
    byte[] pkcs8 = new byte[len];
    System.arraycopy(out, 0, pkcs8, 0, len);
    KeyFactory fact = KeyFactory.getInstance("RSA"); // It seems to work for both RSA and DSA.
    return fact.generatePrivate(new PKCS8EncodedKeySpec(pkcs8));
  }
コード例 #23
0
ファイル: RSACoder.java プロジェクト: xxxggw1985/dubboxdemo
 /**
  * 得到私钥
  *
  * @param key 密钥字符串(经过base64编码)
  * @throws Exception
  */
 public static PrivateKey getPrivateKey(String key) throws Exception {
   byte[] keyBytes;
   keyBytes = Base64.decodeBase64(key);
   PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
   KeyFactory keyFactory = KeyFactory.getInstance("RSA");
   PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
   return privateKey;
 }
コード例 #24
0
 public static PrivateKey loadPrivateKey(String key64) throws GeneralSecurityException {
   byte[] clear = Base64.decode(key64);
   PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear);
   KeyFactory fact = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider());
   PrivateKey priv = fact.generatePrivate(keySpec);
   Arrays.fill(clear, (byte) 0);
   return priv;
 }
コード例 #25
0
ファイル: RSACoder.java プロジェクト: yminggithub/ryf_mms2
 // 私钥加密
 public static byte[] encryptByPrivateKey(byte[] data, byte[] key) throws Exception {
   PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
   KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
   PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
   Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
   cipher.init(Cipher.ENCRYPT_MODE, privateKey);
   return cipher.doFinal(data);
 }
コード例 #26
0
ファイル: RSAUtils.java プロジェクト: whg333/iTool
 /**
  * 使用N、d值还原私钥
  *
  * @param modulus
  * @param privateExponent
  * @return
  * @throws NoSuchAlgorithmException
  * @throws InvalidKeySpecException
  */
 public static PrivateKey getPrivateKey(String modulus, String privateExponent)
     throws NoSuchAlgorithmException, InvalidKeySpecException {
   BigInteger bigIntModulus = new BigInteger(modulus);
   BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
   RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
   KeyFactory keyFactory = KeyFactory.getInstance(RSA);
   PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
   return privateKey;
 }
コード例 #27
0
  protected Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType)
      throws InvalidKeyException, NoSuchAlgorithmException {
    byte[] encoded;
    try {
      if (wrapEngine == null) {
        encoded = engineDoFinal(wrappedKey, 0, wrappedKey.length);
      } else {
        encoded = wrapEngine.unwrap(wrappedKey, 0, wrappedKey.length);
      }
    } catch (InvalidCipherTextException e) {
      throw new InvalidKeyException(e.getMessage());
    } catch (BadPaddingException e) {
      throw new InvalidKeyException(e.getMessage());
    } catch (IllegalBlockSizeException e2) {
      throw new InvalidKeyException(e2.getMessage());
    }

    if (wrappedKeyType == Cipher.SECRET_KEY) {
      return new SecretKeySpec(encoded, wrappedKeyAlgorithm);
    } else if (wrappedKeyAlgorithm.equals("") && wrappedKeyType == Cipher.PRIVATE_KEY) {
      /*
       * The caller doesn't know the algorithm as it is part of
       * the encrypted data.
       */
      try {
        PrivateKeyInfo in = PrivateKeyInfo.getInstance(encoded);

        PrivateKey privKey = BouncyCastleProvider.getPrivateKey(in);

        if (privKey != null) {
          return privKey;
        } else {
          throw new InvalidKeyException(
              "algorithm " + in.getPrivateKeyAlgorithm().getAlgorithm() + " not supported");
        }
      } catch (Exception e) {
        throw new InvalidKeyException("Invalid key encoding.");
      }
    } else {
      try {
        KeyFactory kf =
            KeyFactory.getInstance(wrappedKeyAlgorithm, BouncyCastleProvider.PROVIDER_NAME);

        if (wrappedKeyType == Cipher.PUBLIC_KEY) {
          return kf.generatePublic(new X509EncodedKeySpec(encoded));
        } else if (wrappedKeyType == Cipher.PRIVATE_KEY) {
          return kf.generatePrivate(new PKCS8EncodedKeySpec(encoded));
        }
      } catch (NoSuchProviderException e) {
        throw new InvalidKeyException("Unknown key type " + e.getMessage());
      } catch (InvalidKeySpecException e2) {
        throw new InvalidKeyException("Unknown key type " + e2.getMessage());
      }

      throw new InvalidKeyException("Unknown key type " + wrappedKeyType);
    }
  }
コード例 #28
0
 /**
  * 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);
   }
 }
コード例 #29
0
ファイル: DSATest.java プロジェクト: SreejitS/isaacyang1988
  private void testNONEwithECDSA239bitPrime() throws Exception {
    ECCurve curve =
        new ECCurve.Fp(
            new BigInteger(
                "883423532389192164791648750360308885314476597252960362792450860609699839"), // q
            new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
            new BigInteger(
                "6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b

    ECParameterSpec spec =
        new ECParameterSpec(
            curve,
            curve.decodePoint(
                Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
            new BigInteger(
                "883423532389192164791648750360308884807550341691627752275345424702807307")); // n

    ECPrivateKeySpec priKey =
        new ECPrivateKeySpec(
            new BigInteger(
                "876300101507107567501066130761671078357010671067781776716671676178726717"), // d
            spec);

    ECPublicKeySpec pubKey =
        new ECPublicKeySpec(
            curve.decodePoint(
                Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
            spec);

    Signature sgr = Signature.getInstance("NONEwithECDSA", "BC");
    KeyFactory f = KeyFactory.getInstance("ECDSA", "BC");
    PrivateKey sKey = f.generatePrivate(priKey);
    PublicKey vKey = f.generatePublic(pubKey);
    SecureRandom k = new SecureRandom();

    byte[] message = "abc".getBytes();
    byte[] sig =
        Hex.decode(
            "3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e64cb19604be06c57e761b3de5518f71de0f6e0cd2df677cec8a6ffcb690d");

    checkMessage(sgr, sKey, vKey, message, sig);

    message = "abcdefghijklmnopqrstuvwxyz".getBytes();
    sig =
        Hex.decode(
            "3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e43fd65b3363d76aabef8630572257dbb67c82818ad9fad31256539b1b02c");

    checkMessage(sgr, sKey, vKey, message, sig);

    message = "a very very long message gauranteed to cause an overflow".getBytes();
    sig =
        Hex.decode(
            "3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e7d5be84b22937a1691859a3c6fe45ed30b108574431d01b34025825ec17a");

    checkMessage(sgr, sKey, vKey, message, sig);
  }
コード例 #30
0
 @Override
 protected PrivateKey createInstance() throws Exception {
   try (final InputStream privKey = this.location.getInputStream()) {
     final byte[] bytes = new byte[privKey.available()];
     privKey.read(bytes);
     final PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(bytes);
     final KeyFactory factory = KeyFactory.getInstance(this.algorithm);
     return factory.generatePrivate(privSpec);
   }
 }