Java 类java.security.KeyFactory 实例源码

项目:FApkSigner    文件:V2SchemeSigner.java   
private static byte[] encodePublicKey(PublicKey publicKey)
        throws InvalidKeyException, NoSuchAlgorithmException {
    byte[] encodedPublicKey = null;
    if ("X.509".equals(publicKey.getFormat())) {
        encodedPublicKey = publicKey.getEncoded();
    }
    if (encodedPublicKey == null) {
        try {
            encodedPublicKey =
                    KeyFactory.getInstance(publicKey.getAlgorithm())
                            .getKeySpec(publicKey, X509EncodedKeySpec.class)
                            .getEncoded();
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(
                    "Failed to obtain X.509 encoded form of public key " + publicKey
                            + " of class " + publicKey.getClass().getName(),
                    e);
        }
    }
    if ((encodedPublicKey == null) || (encodedPublicKey.length == 0)) {
        throw new InvalidKeyException(
                "Failed to obtain X.509 encoded form of public key " + publicKey
                        + " of class " + publicKey.getClass().getName());
    }
    return encodedPublicKey;
}
项目:godlibrary    文件:RSAUtlis.java   
/**
 * 校验数字签名
 *
 * @param data      加密数据
 * @param publicKey 公钥
 * @param sign      数字签名
 * @return
 * @throws Exception
 */
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
    //解密公钥
    byte[] keyBytes = Base64.decode(publicKey.getBytes(), Base64.DEFAULT);
    //构造X509EncodedKeySpec对象
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
    //指定加密算法
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    //取公钥匙对象
    PublicKey publicKey2 = keyFactory.generatePublic(x509EncodedKeySpec);

    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initVerify(publicKey2);
    signature.update(data);
    //验证签名是否正常
    return signature.verify(Base64.decode(sign, Base64.DEFAULT));

}
项目:JBase    文件:RsaUtils.java   
/**
 * 私钥加密
 *
 * @param data       待加密数据
 * @param privateKey 密钥
 * @return byte[] 加密数据
 */
private static byte[] encryptByPrivate(byte[] data, byte[] privateKey) {
    byte[] result = null;
    // 得到私钥
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
    try {
        KeyFactory kf = KeyFactory.getInstance(RSA);
        PrivateKey keyPrivate = kf.generatePrivate(keySpec);
        // 数据加密
        Cipher cipher = Cipher.getInstance(ECB_PKCS1_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, keyPrivate);
        result = cipher.doFinal(data);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("RSA加密", "私钥加密失败");
    }
    return result;
}
项目:OpenJSharp    文件:BasicChecker.java   
/**
 * Internal method to create a new key with inherited key parameters.
 *
 * @param keyValueKey key from which to obtain key value
 * @param keyParamsKey key from which to obtain key parameters
 * @return new public key having value and parameters
 * @throws CertPathValidatorException if keys are not appropriate types
 * for this operation
 */
static PublicKey makeInheritedParamsKey(PublicKey keyValueKey,
    PublicKey keyParamsKey) throws CertPathValidatorException
{
    if (!(keyValueKey instanceof DSAPublicKey) ||
        !(keyParamsKey instanceof DSAPublicKey))
        throw new CertPathValidatorException("Input key is not " +
                                             "appropriate type for " +
                                             "inheriting parameters");
    DSAParams params = ((DSAPublicKey)keyParamsKey).getParams();
    if (params == null)
        throw new CertPathValidatorException("Key parameters missing");
    try {
        BigInteger y = ((DSAPublicKey)keyValueKey).getY();
        KeyFactory kf = KeyFactory.getInstance("DSA");
        DSAPublicKeySpec ks = new DSAPublicKeySpec(y,
                                                   params.getP(),
                                                   params.getQ(),
                                                   params.getG());
        return kf.generatePublic(ks);
    } catch (GeneralSecurityException e) {
        throw new CertPathValidatorException("Unable to generate key with" +
                                             " inherited parameters: " +
                                             e.getMessage(), e);
    }
}
项目:springboot-training    文件:RSACoder.java   
/**
 * 解密<br>
 * 用私钥解密
 * 
 * @param data
 * @param key
 * @return
 * @throws Exception
 */
protected static byte[] decryptByPrivateKey(byte[] data, String key) {
    try {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据解密
        // Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        Cipher cipher = Cipher.getInstance(RSA_java);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    } catch (Exception e) {
        throw new ZhhrUtilException("用私钥解密" + e.getMessage());
    }
}
项目:BibliotecaPS    文件:ExportControlled.java   
public static RSAPublicKey decodeRSAPublicKey(String key, ExceptionInterceptor interceptor) throws SQLException {

        try {
            if (key == null) {
                throw new SQLException("key parameter is null");
            }

            int offset = key.indexOf("\n") + 1;
            int len = key.indexOf("-----END PUBLIC KEY-----") - offset;

            // TODO: use standard decoders with Java 6+
            byte[] certificateData = Base64Decoder.decode(key.getBytes(), offset, len);

            X509EncodedKeySpec spec = new X509EncodedKeySpec(certificateData);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return (RSAPublicKey) kf.generatePublic(spec);
        } catch (Exception ex) {
            throw SQLError.createSQLException("Unable to decode public key", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, ex, interceptor);
        }
    }
项目:GitHub    文件:Codec.java   
/**
 * 用公钥解密
 *
 * @param data
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] decryptByPublicKey(byte[] data, String key)
        throws Exception {
    byte[] keyBytes = BASE64.decode(key);       // 对密钥解密

    // 取得公钥
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());
    Key publicKey = keyFactory.generatePublic(x509KeySpec);

    // 对数据解密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, publicKey);

    return cipher.doFinal(data);
}
项目:GroupControlDroidClient    文件:RSASignature.java   
public static String sign(String content, String privateKey) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                Base64.decode(privateKey));
        KeyFactory keyf = KeyFactory.getInstance("RSA");
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);
        java.security.Signature signature = java.security.Signature
                .getInstance(SIGN_ALGORITHMS);
        signature.initSign(priKey);
        signature.update(content.getBytes());
        byte[] signed = signature.sign();
        return Base64.encode(signed);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
项目:Wurst-MC-1.12    文件:Encryption.java   
private KeyPair loadRsaKeys(Path publicFile, Path privateFile)
    throws GeneralSecurityException, ReflectiveOperationException,
    IOException
{
    KeyFactory factory = KeyFactory.getInstance("RSA");

    // load public key
    PublicKey publicKey;
    try(ObjectInputStream in =
        new ObjectInputStream(Files.newInputStream(publicFile)))
    {
        publicKey = factory.generatePublic(new RSAPublicKeySpec(
            (BigInteger)in.readObject(), (BigInteger)in.readObject()));
    }

    // load private key
    PrivateKey privateKey;
    try(ObjectInputStream in =
        new ObjectInputStream(Files.newInputStream(privateFile)))
    {
        privateKey = factory.generatePrivate(new RSAPrivateKeySpec(
            (BigInteger)in.readObject(), (BigInteger)in.readObject()));
    }

    return new KeyPair(publicKey, privateKey);
}
项目:Renrentou    文件:Codec.java   
/**
 * 用公钥加密
 *
 * @param data
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] encryptByPublicKey(byte[] data, String key)
        throws Exception {
    byte[] keyBytes = BASE64.decode(key);   // 对公钥解密

    // 取得公钥
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());
    Key publicKey = keyFactory.generatePublic(x509KeySpec);

    // 对数据加密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    return cipher.doFinal(data);
}
项目:sample-acmegifts    文件:JWTVerifier.java   
/**
 * Get the public key that is used to verify the JWT from the user service. We assume the key is
 * an RSA key.
 *
 * @throws NoSuchAlgorithmException
 */
private PublicKey getPublicKey()
    throws Base64Exception, InvalidKeySpecException, NoSuchAlgorithmException {
  String url =
      "https://" + libertyHostname + ":" + libertySslPort + "/jwt/ibm/api/jwtUserBuilder/jwk";
  Response response = processRequest(url, "GET", null, null);
  assertEquals(
      "HTTP response code should have been " + Status.OK.getStatusCode() + ".",
      Status.OK.getStatusCode(),
      response.getStatus());

  // Liberty returns the keys in an array.  We'll grab the first one (there
  // should only be one).
  JsonObject jwkResponse = toJsonObj(response.readEntity(String.class));
  JsonArray jwkArray = jwkResponse.getJsonArray("keys");
  JsonObject jwk = jwkArray.getJsonObject(0);
  BigInteger modulus = new BigInteger(1, Base64Utility.decode(jwk.getString("n"), true));
  BigInteger publicExponent = new BigInteger(1, Base64Utility.decode(jwk.getString("e"), true));
  return KeyFactory.getInstance("RSA")
      .generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
}
项目:k-framework    文件:RSA.java   
/**
* RSA签名
* @param content 待签名数据
* @param privateKey 商户私钥
* @param input_charset 编码格式
* @return 签名值
*/
public static String sign(String content, String privateKey, String input_charset)
{
       try 
       {
        PKCS8EncodedKeySpec priPKCS8    = new PKCS8EncodedKeySpec( Base64.decode(privateKey) ); 
        KeyFactory keyf                 = KeyFactory.getInstance("RSA");
        PrivateKey priKey               = keyf.generatePrivate(priPKCS8);

           java.security.Signature signature = java.security.Signature
               .getInstance(SIGN_ALGORITHMS);

           signature.initSign(priKey);
           signature.update( content.getBytes(input_charset) );

           byte[] signed = signature.sign();

           return Base64.encode(signed);
       }
       catch (Exception e) 
       {
        e.printStackTrace();
       }

       return null;
   }
项目:CS4160-trustchain-android    文件:Key.java   
/**
 * Load a private key from a base64 encoded string
 * @param key The base64 encoded key
 * @return The private key
 */
public static PrivateKey loadPrivateKey(String key) {
    KeyFactory kf = getKeyFactory();
    if(kf == null) {
        return null;
    }

    byte[] rawKey = Base64.decode(key, Base64.DEFAULT);
    PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(rawKey);
    try {
        return kf.generatePrivate(ks);
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }
    return null;
}
项目:edge-jwt-sample    文件:JWTGenerator.java   
private PublicKey getDERPublicKeyFromPEM(String key) throws Exception {
    try {
        // strip of header, footer, newlines, whitespaces
        String publicKeyPEM = key
                .replace("-----BEGIN PUBLIC KEY-----", "")
                .replace("-----END PUBLIC KEY-----", "")
                .replaceAll("\\s", "");

        // decode to get the binary DER representation
        byte[] publicKeyDER = Base64.getDecoder().decode(publicKeyPEM);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyDER));
        return publicKey;
    } catch (Exception e) {
        throw new InvalidConfig("Invalid JWE public key");
    }
}
项目:Renrentou    文件:Codec.java   
/**
 * 用公钥解密
 *
 * @param data
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] decryptByPublicKey(byte[] data, String key)
        throws Exception {
    byte[] keyBytes = BASE64.decode(key);       // 对密钥解密

    // 取得公钥
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());
    Key publicKey = keyFactory.generatePublic(x509KeySpec);

    // 对数据解密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, publicKey);

    return cipher.doFinal(data);
}
项目:VerifySignedJar    文件:VerfiyPKCS7Info.java   
/**
 * 从hex string 生成私钥
 * 
 * @param stringN
 * @param stringD
 * @return 构造好的私钥
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PrivateKey createPrivateKey(String stringN, String stringD)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    try {
        BigInteger N = new BigInteger(stringN, 16); // hex base
        BigInteger D = new BigInteger(stringD, 16); // hex base

        RSAPrivateKeySpec spec = new RSAPrivateKeySpec(N, D);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(spec);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
项目:mi-firma-android    文件:JseCryptoHelper.java   
private static Key loadEcPublicKey(final byte [] pubKey,
                                      final EcCurve curveName) throws NoSuchAlgorithmException,
                                                                      InvalidKeySpecException {
    final ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveName.toString());
    KeyFactory kf;
    try {
        kf = KeyFactory.getInstance(ECDH, BouncyCastleProvider.PROVIDER_NAME);
    }
    catch (final NoSuchProviderException e) {
        kf = KeyFactory.getInstance(ECDH);
    }
    final ECNamedCurveSpec params = new ECNamedCurveSpec(curveName.toString(), spec.getCurve(), spec.getG(), spec.getN());
    final ECPoint point =  ECPointUtil.decodePoint(params.getCurve(), pubKey);
    final java.security.spec.ECPublicKeySpec pubKeySpec = new java.security.spec.ECPublicKeySpec(point, params);
    return kf.generatePublic(pubKeySpec);
}
项目:BaseClient    文件:CryptManager.java   
/**
 * Create a new PublicKey from encoded X.509 data
 */
public static PublicKey decodePublicKey(byte[] encodedKey)
{
    try
    {
        EncodedKeySpec encodedkeyspec = new X509EncodedKeySpec(encodedKey);
        KeyFactory keyfactory = KeyFactory.getInstance("RSA");
        return keyfactory.generatePublic(encodedkeyspec);
    }
    catch (NoSuchAlgorithmException var3)
    {
        ;
    }
    catch (InvalidKeySpecException var4)
    {
        ;
    }

    LOGGER.error("Public key reconstitute failed!");
    return null;
}
项目:BaseClient    文件:CryptManager.java   
/**
 * Create a new PublicKey from encoded X.509 data
 */
public static PublicKey decodePublicKey(byte[] encodedKey)
{
    try
    {
        EncodedKeySpec encodedkeyspec = new X509EncodedKeySpec(encodedKey);
        KeyFactory keyfactory = KeyFactory.getInstance("RSA");
        return keyfactory.generatePublic(encodedkeyspec);
    }
    catch (NoSuchAlgorithmException var3)
    {
        ;
    }
    catch (InvalidKeySpecException var4)
    {
        ;
    }

    LOGGER.error("Public key reconstitute failed!");
    return null;
}
项目:GroupControlDroidClient    文件:RSASignature.java   
/**
 * RSA签名
 * 
 * @param content
 *            待签名数据
 * @param privateKey
 *            商户私钥
 * @param encode
 *            字符集编码
 * @return 签名值
 */
public static String sign(String content, String privateKey, String encode) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                Base64.decode(privateKey));

        KeyFactory keyf = KeyFactory.getInstance("RSA");
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);

        java.security.Signature signature = java.security.Signature
                .getInstance(SIGN_ALGORITHMS);

        signature.initSign(priKey);
        signature.update(content.getBytes(encode));

        byte[] signed = signature.sign();

        return Base64.encode(signed);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
项目:af-pay    文件:SignUtils.java   
public static String sign(String content, String privateKey, boolean rsa2) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
            Base64.decode(privateKey));
        KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);

        java.security.Signature signature = java.security.Signature
            .getInstance(getAlgorithms(rsa2));

        signature.initSign(priKey);
        signature.update(content.getBytes(DEFAULT_CHARSET));

        byte[] signed = signature.sign();

        return Base64.encode(signed);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
项目:JBase    文件:RsaUtils.java   
/**
 * 使用私钥进行解密
 */
private static byte[] decryptByPrivate(byte[] encrypted, byte[] privateKey) {
    byte[] result = null;
    // 得到私钥
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
    try {
        KeyFactory kf = KeyFactory.getInstance(RSA);
        PrivateKey keyPrivate = kf.generatePrivate(keySpec);

        // 解密数据
        Cipher cp = Cipher.getInstance(ECB_PKCS1_PADDING);
        cp.init(Cipher.DECRYPT_MODE, keyPrivate);
        result = cp.doFinal(encrypted);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("RSA加密", "私钥解密失败");
    }
    return result;
}
项目:pay4j    文件:RSA.java   
/**
 * RSA验签名检查
 *
 * @param content        待签名数据
 * @param sign           签名值
 * @param ali_public_key 支付宝公钥
 * @param input_charset  编码格式
 * @return 布尔值
 */
public static boolean verify(String content, String sign, String ali_public_key, String input_charset) {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] encodedKey = Base64.decode(ali_public_key);
        PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));


        java.security.Signature signature = java.security.Signature
                .getInstance(SIGN_ALGORITHMS);

        signature.initVerify(pubKey);
        signature.update(content.getBytes(input_charset));

        return signature.verify(Base64.decode(sign));

    } catch (Exception e) {
        e.printStackTrace();
    }

    return false;
}
项目:holon-core    文件:KeysReader.java   
/**
 * Read a private key from given bytes array in PKCS8 format
 * @param algorithm Algorithm to use (for example RSA)
 * @param key Key bytes
 * @return PrivateKey
 * @throws SecurityException Error reading key
 */
public static PrivateKey readPrivateKey(String algorithm, byte[] key) throws SecurityException {
    if (algorithm == null) {
        throw new IllegalArgumentException("Null algorithm name");
    }
    if (key == null || key.length == 0) {
        throw new IllegalArgumentException("Null key bytes");
    }
    try {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        return keyFactory.generatePrivate(keySpec);
    } catch (Exception e) {
        throw new SecurityException("Failed to read PKCS8 private key using algorithm " + algorithm, e);
    }
}
项目:automat    文件:RSACoder.java   
/**
 * 校验
 * 
 * @param data 待校验数据
 * @param publicKey 公钥
 * @param sign 数字签名
 * @return boolean 校验成功返回true 失败返回false
 * @throws Exception
 */
public static boolean verify(byte[] data, byte[] publicKey, byte[] sign) throws Exception {
    // 转换公钥材料
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
    // 实例化密钥工厂
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // 生成公钥
    PublicKey pubKey = keyFactory.generatePublic(keySpec);
    // 实例化Signature
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    // 初始化Signature
    signature.initVerify(pubKey);
    // 更新
    signature.update(data);
    // 验证
    return signature.verify(sign);
}
项目:aaden-pay    文件:LianlianTraderRSAUtil.java   
/**
 * 签名处理
 * 
 * @param prikeyvalue
 *            :私钥
 * @param sign_str
 *            :签名源内容
 * @return
 */
public static String sign(String prikeyvalue, String sign_str) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(LianlianBase64.getBytesBASE64(prikeyvalue));
        KeyFactory keyf = KeyFactory.getInstance("RSA");
        PrivateKey myprikey = keyf.generatePrivate(priPKCS8);
        // 用私钥对信息生成数字签名
        java.security.Signature signet = java.security.Signature.getInstance("MD5withRSA");
        signet.initSign(myprikey);
        signet.update(sign_str.getBytes("UTF-8"));
        byte[] signed = signet.sign(); // 对信息的数字签名
        return new String(org.apache.commons.codec.binary.Base64.encodeBase64(signed));
    } catch (java.lang.Exception e) {
        e.printStackTrace();
    }
    return null;
}
项目:QuanMinTV    文件:SignUtils.java   
public static String sign(String content, String privateKey, boolean rsa2) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                Base64.decode(privateKey));
        KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);

        java.security.Signature signature = java.security.Signature
                .getInstance(getAlgorithms(rsa2));

        signature.initSign(priKey);
        signature.update(content.getBytes(DEFAULT_CHARSET));

        byte[] signed = signature.sign();

        return Base64.encode(signed);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
项目:19porn    文件:Codec.java   
/**
 * 用私钥加密
 *
 * @param data
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] encryptByPrivateKey(byte[] data, String key)
        throws Exception {

    byte[] keyBytes = BASE64.decode(key);   // 对密钥解密

    // 取得私钥
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());
    Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

    // 对数据加密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, privateKey);

    return cipher.doFinal(data);
}
项目:JAVA-    文件:RSACoder.java   
/**
 * 签名
 * 
 * @param data 待签名数据
 * @param privateKey 私钥
 * @return byte[] 数字签名
 * @throws Exception
 */
public static byte[] sign(byte[] data, byte[] privateKey) throws Exception {
    // 转换私钥材料
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
    // 实例化密钥工厂
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // 取私钥匙对象
    PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
    // 实例化Signature
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    // 初始化Signature
    signature.initSign(priKey);
    // 更新
    signature.update(data);
    // 签名
    return signature.sign();
}
项目:spring-boot-actuator-dashboard    文件:JwtTokenConverter.java   
public void setSigningKey(String key) throws Exception {
    this.signingKey = key;
    key = key.trim();

    key = key.replace("-----BEGIN RSA PRIVATE KEY-----\n", "")
            .replace("-----END RSA PRIVATE KEY-----", "").trim().replace("\n", "");
    byte[] encoded = Base64Utils.decodeFromString(key);
    DerInputStream derInputStream = new DerInputStream(encoded);
    DerValue[] seq = derInputStream.getSequence(0);

    BigInteger modulus = seq[1].getBigInteger();
    BigInteger publicExp = seq[2].getBigInteger();
    BigInteger privateExp = seq[3].getBigInteger();
    BigInteger prime1 = seq[4].getBigInteger();
    BigInteger prime2 = seq[5].getBigInteger();
    BigInteger exp1 = seq[6].getBigInteger();
    BigInteger exp2 = seq[7].getBigInteger();
    BigInteger crtCoef = seq[8].getBigInteger();

    RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp,
            privateExp, prime1, prime2, exp1, exp2, crtCoef);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    this.signer = new RSASSASigner(kf.generatePrivate(keySpec));
}
项目:LuaViewPlayground    文件:VerifyUtil.java   
/**
 * read public key
 *
 * @param filename
 * @return
 */
private static PublicKey generatePublicKey(final String filename) {
    try {
        File f = new File(filename);
        FileInputStream fis = new FileInputStream(f);
        DataInputStream dis = new DataInputStream(fis);
        byte[] keyBytes = new byte[(int) f.length()];
        dis.readFully(keyBytes);
        dis.close();

        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance(ALGORITHM_RSA);
        return kf.generatePublic(spec);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
项目:openjdk-jdk10    文件:DOMKeyValue.java   
PublicKey unmarshalKeyValue(Element kvtElem)
    throws MarshalException
{
    if (rsakf == null) {
        try {
            rsakf = KeyFactory.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException
                ("unable to create RSA KeyFactory: " + e.getMessage());
        }
    }
    Element modulusElem = DOMUtils.getFirstChildElement(kvtElem,
                                                        "Modulus");
    modulus = new DOMCryptoBinary(modulusElem.getFirstChild());
    Element exponentElem = DOMUtils.getNextSiblingElement(modulusElem,
                                                          "Exponent");
    exponent = new DOMCryptoBinary(exponentElem.getFirstChild());
    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus.getBigNum(),
                                                 exponent.getBigNum());
    return generatePublicKey(rsakf, spec);
}
项目:quilt    文件:RsaSha256SignatureTest.java   
/**
 * Required args Constructor.
 *
 * @param testVectorPair A {@link RsaTestVectorPair} to populate this test.
 * @throws Exception If anything goes wrong.
 */
public RsaSha256SignatureTest(final RsaTestVectorPair testVectorPair) throws Exception {
  Objects.requireNonNull(testVectorPair);
  this.keyFactory = KeyFactory.getInstance("RSA");
  this.rsaSigner = testVectorPair.getSignature();
  this.rsaJsonTestVector = testVectorPair.getRsaTestVectorJson();
}
项目:iBase4J    文件:RSACoder.java   
/**
 * 公钥解密
 * 
 * @param data 待解密数据
 * @param key 公钥
 * @return byte[] 解密数据
 * @throws Exception
 */
public static byte[] decryptByPublicKey(byte[] data, byte[] key) throws Exception {
    // 取得公钥
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // 生成公钥
    PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
    // 对数据解密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, publicKey);
    return cipher.doFinal(data);
}
项目:JungleTree    文件:LoginValidator.java   
private static ECPublicKey getECX509PublicKey(String base64Key) {
    try {
        return (ECPublicKey) KeyFactory.getInstance("ECDH", "BC").generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(base64Key)));
    } catch (InvalidKeySpecException | NoSuchProviderException | NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }
}
项目:quickstart    文件:AssertionGenerator.java   
/**
 * Extracts private key (predictive_services.pem) contents
 */
private static PrivateKey getPrivateKey(String privateKeyBase64) {
  String privKeyPEM = privateKeyBase64.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
  privKeyPEM = privKeyPEM.replace("\n-----END RSA PRIVATE KEY-----", "");

  // Base64 decode the data
  byte[] encoded = Base64.decodeBase64(privKeyPEM);

  try {
    DerInputStream derReader = new DerInputStream(encoded);
    DerValue[] seq = derReader.getSequence(0);

    if (seq.length < 9) {
      throw new GeneralSecurityException("Could not read private key");
    }

    // skip version seq[0];
    BigInteger modulus = seq[1].getBigInteger();
    BigInteger publicExp = seq[2].getBigInteger();
    BigInteger privateExp = seq[3].getBigInteger();
    BigInteger primeP = seq[4].getBigInteger();
    BigInteger primeQ = seq[5].getBigInteger();
    BigInteger expP = seq[6].getBigInteger();
    BigInteger expQ = seq[7].getBigInteger();
    BigInteger crtCoeff = seq[8].getBigInteger();

    RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp,
        primeP, primeQ, expP, expQ, crtCoeff);

    KeyFactory factory = KeyFactory.getInstance("RSA");
    return factory.generatePrivate(keySpec);
  } catch (IOException | GeneralSecurityException e) {
    Throwables.propagate(e);
  }
  return null;
}
项目:edge-jwt-sample    文件:JWTValidatorTest.java   
private PublicKey getDERPublicKeyFromPEM(String key) {
    try {
        // strip of header, footer, newlines, whitespaces
        String publicKeyPEM = key
                .replace("-----BEGIN PUBLIC KEY-----", "")
                .replace("-----END PUBLIC KEY-----", "")
                .replaceAll("\\s", "");

        // decode to get the binary DER representation
        byte[] publicKeyDER = Base64.getDecoder().decode(publicKeyPEM);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyDER));
        return publicKey;
    } catch (Exception e) {
        return null;
    }
}
项目:Zen-of-Affair    文件:DHKeyGenerator.java   
public void generateKey(DHPublicKey publicKey) throws Exception
{
    byte[] key = publicKey.getEncoded();
    X509EncodedKeySpec X509KeySpec = new X509EncodedKeySpec(key);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    PublicKey pubKey = keyFactory.generatePublic(X509KeySpec);
    DHParameterSpec dhParameterSpec = ((DHPublicKey)pubKey).getParams();
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    keyPairGenerator.initialize(KEY_SIZE);
    keyPair = keyPairGenerator.generateKeyPair();
}
项目:GitHub    文件:Codec.java   
/**
 * 用私钥解密
 *
 * @param data
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] decryptByPrivateKey(byte[] data, String key)
        throws Exception {
    byte[] keyBytes = BASE64.decode(key);   // 对密钥解密

    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);   // 取得私钥
    KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());
    Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

    // 对数据解密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    return cipher.doFinal(data);
}
项目:CS4160-trustchain-android    文件:Key.java   
private static KeyFactory getKeyFactory() {
    try {
        return KeyFactory.getInstance("ECDSA");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}