当前位置: 首页>>代码示例>>Java>>正文


Java KeyFactory类代码示例

本文整理汇总了Java中java.security.KeyFactory的典型用法代码示例。如果您正苦于以下问题:Java KeyFactory类的具体用法?Java KeyFactory怎么用?Java KeyFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


KeyFactory类属于java.security包,在下文中一共展示了KeyFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: encodePublicKey

import java.security.KeyFactory; //导入依赖的package包/类
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;
}
 
开发者ID:F8LEFT,项目名称:FApkSigner,代码行数:27,代码来源:V2SchemeSigner.java

示例2: verify

import java.security.KeyFactory; //导入依赖的package包/类
/**
 * 校验数字签名
 *
 * @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));

}
 
开发者ID:abook23,项目名称:godlibrary,代码行数:27,代码来源:RSAUtlis.java

示例3: setSigningKey

import java.security.KeyFactory; //导入依赖的package包/类
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));
}
 
开发者ID:making,项目名称:spring-boot-actuator-dashboard,代码行数:25,代码来源:JwtTokenConverter.java

示例4: encryptByPrivate

import java.security.KeyFactory; //导入依赖的package包/类
/**
 * 私钥加密
 *
 * @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;
}
 
开发者ID:JJS-CN,项目名称:JBase,代码行数:25,代码来源:RsaUtils.java

示例5: makeInheritedParamsKey

import java.security.KeyFactory; //导入依赖的package包/类
/**
 * 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);
    }
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:35,代码来源:BasicChecker.java

示例6: decryptByPrivateKey

import java.security.KeyFactory; //导入依赖的package包/类
/**
 * 解密<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());
	}
}
 
开发者ID:wooui,项目名称:springboot-training,代码行数:27,代码来源:RSACoder.java

示例7: decodeRSAPublicKey

import java.security.KeyFactory; //导入依赖的package包/类
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);
        }
    }
 
开发者ID:rafallis,项目名称:BibliotecaPS,代码行数:21,代码来源:ExportControlled.java

示例8: decryptByPublicKey

import java.security.KeyFactory; //导入依赖的package包/类
/**
 * 用公钥解密
 *
 * @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);
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:24,代码来源:Codec.java

示例9: sign

import java.security.KeyFactory; //导入依赖的package包/类
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;
}
 
开发者ID:GroupControlDroid,项目名称:GroupControlDroidClient,代码行数:18,代码来源:RSASignature.java

示例10: loadRsaKeys

import java.security.KeyFactory; //导入依赖的package包/类
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);
}
 
开发者ID:Wurst-Imperium,项目名称:Wurst-MC-1.12,代码行数:27,代码来源:Encryption.java

示例11: encryptByPublicKey

import java.security.KeyFactory; //导入依赖的package包/类
/**
 * 用公钥加密
 *
 * @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);
}
 
开发者ID:ruiqiao2017,项目名称:Renrentou,代码行数:24,代码来源:Codec.java

示例12: getPublicKey

import java.security.KeyFactory; //导入依赖的package包/类
/**
 * 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));
}
 
开发者ID:OpenLiberty,项目名称:sample-acmegifts,代码行数:27,代码来源:JWTVerifier.java

示例13: sign

import java.security.KeyFactory; //导入依赖的package包/类
/**
* 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;
   }
 
开发者ID:superkoh,项目名称:k-framework,代码行数:33,代码来源:RSA.java

示例14: loadPrivateKey

import java.security.KeyFactory; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:wkmeijer,项目名称:CS4160-trustchain-android,代码行数:21,代码来源:Key.java

示例15: getDERPublicKeyFromPEM

import java.security.KeyFactory; //导入依赖的package包/类
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");
	}
}
 
开发者ID:gahana,项目名称:edge-jwt-sample,代码行数:19,代码来源:JWTGenerator.java


注:本文中的java.security.KeyFactory类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。