當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。