Java Code Examples for java.security.KeyFactory

The following are top voted examples for showing how to use java.security.KeyFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: FApkSigner   File: V2SchemeSigner.java   View source code 8 votes vote down vote up
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;
}
 
Example 2
Project: spring-boot-actuator-dashboard   File: JwtTokenConverter.java   View source code 7 votes vote down vote up
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));
}
 
Example 3
Project: godlibrary   File: RSAUtlis.java   View source code 7 votes vote down vote up
/**
 * 校验数字签名
 *
 * @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));

}
 
Example 4
Project: JBase   File: RsaUtils.java   View source code 6 votes vote down vote up
/**
 * 私钥加密
 *
 * @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;
}
 
Example 5
Project: OpenJSharp   File: BasicChecker.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 6
Project: springboot-training   File: RSACoder.java   View source code 6 votes vote down vote up
/**
 * 解密<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());
	}
}
 
Example 7
Project: BibliotecaPS   File: ExportControlled.java   View source code 6 votes vote down vote up
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);
        }
    }
 
Example 8
Project: GitHub   File: Codec.java   View source code 6 votes vote down vote up
/**
 * 用公钥解密
 *
 * @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);
}
 
Example 9
Project: GroupControlDroidClient   File: RSASignature.java   View source code 6 votes vote down vote up
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;
}
 
Example 10
Project: Wurst-MC-1.12   File: Encryption.java   View source code 6 votes vote down vote up
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);
}
 
Example 11
Project: Renrentou   File: Codec.java   View source code 6 votes vote down vote up
/**
 * 用公钥加密
 *
 * @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);
}
 
Example 12
Project: sample-acmegifts   File: JWTVerifier.java   View source code 6 votes vote down vote up
/**
 * 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));
}
 
Example 13
Project: k-framework   File: RSA.java   View source code 6 votes vote down vote up
/**
* 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;
   }
 
Example 14
Project: CS4160-trustchain-android   File: Key.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 15
Project: edge-jwt-sample   File: JWTGenerator.java   View source code 6 votes vote down vote up
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");
	}
}
 
Example 16
Project: Renrentou   File: Codec.java   View source code 6 votes vote down vote up
/**
 * 用公钥解密
 *
 * @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);
}
 
Example 17
Project: VerifySignedJar   File: VerfiyPKCS7Info.java   View source code 6 votes vote down vote up
/**
 * 从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;
}
 
Example 18
Project: mi-firma-android   File: JseCryptoHelper.java   View source code 6 votes vote down vote up
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);
}
 
Example 19
Project: BaseClient   File: CryptManager.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 20
Project: BaseClient   File: CryptManager.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 21
Project: GroupControlDroidClient   File: RSASignature.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 22
Project: af-pay   File: SignUtils.java   View source code 6 votes vote down vote up
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;
}
 
Example 23
Project: JBase   File: RsaUtils.java   View source code 6 votes vote down vote up
/**
 * 使用私钥进行解密
 */
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;
}
 
Example 24
Project: pay4j   File: RSA.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 25
Project: holon-core   File: KeysReader.java   View source code 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 26
Project: automat   File: RSACoder.java   View source code 6 votes vote down vote up
/**
 * 校验
 * 
 * @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);
}
 
Example 27
Project: aaden-pay   File: LianlianTraderRSAUtil.java   View source code 6 votes vote down vote up
/**
 * 签名处理
 * 
 * @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;
}
 
Example 28
Project: QuanMinTV   File: SignUtils.java   View source code 6 votes vote down vote up
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;
}
 
Example 29
Project: 19porn   File: Codec.java   View source code 6 votes vote down vote up
/**
 * 用私钥加密
 *
 * @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);
}
 
Example 30
Project: JAVA-   File: RSACoder.java   View source code 6 votes vote down vote up
/**
 * 签名
 * 
 * @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();
}
 
Example 31
Project: LuaViewPlayground   File: VerifyUtil.java   View source code 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 32
Project: openjdk-jdk10   File: DOMKeyValue.java   View source code 6 votes vote down vote up
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);
}
 
Example 33
Project: quilt   File: RsaSha256SignatureTest.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 34
Project: iBase4J   File: RSACoder.java   View source code 5 votes vote down vote up
/**
 * 公钥解密
 * 
 * @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);
}
 
Example 35
Project: JungleTree   File: LoginValidator.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 36
Project: quickstart   File: AssertionGenerator.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 37
Project: edge-jwt-sample   File: JWTValidatorTest.java   View source code 5 votes vote down vote up
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;
	}
}
 
Example 38
Project: Zen-of-Affair   File: DHKeyGenerator.java   View source code 5 votes vote down vote up
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();
}
 
Example 39
Project: GitHub   File: Codec.java   View source code 5 votes vote down vote up
/**
 * 用私钥解密
 *
 * @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);
}
 
Example 40
Project: CS4160-trustchain-android   File: Key.java   View source code 5 votes vote down vote up
private static KeyFactory getKeyFactory() {
    try {
        return KeyFactory.getInstance("ECDSA");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}