當前位置: 首頁>>代碼示例>>Java>>正文


Java InvalidKeySpecException類代碼示例

本文整理匯總了Java中java.security.spec.InvalidKeySpecException的典型用法代碼示例。如果您正苦於以下問題:Java InvalidKeySpecException類的具體用法?Java InvalidKeySpecException怎麽用?Java InvalidKeySpecException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


InvalidKeySpecException類屬於java.security.spec包,在下文中一共展示了InvalidKeySpecException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: createKeyManagerFactory

import java.security.spec.InvalidKeySpecException; //導入依賴的package包/類
private static KeyManagerFactory createKeyManagerFactory(
	final String clientCertificateFileName, final String clientKeyFileName, final String clientKeyPassword) 
	throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException
{
	// Creates a key manager factory
	// Load and create the client certificate
	final X509Certificate clientCertificate = createX509CertificateFromFile(clientCertificateFileName);	
	// Load the private client key
	final PrivateKey privateKey = createPrivateKeyFromPemFile(clientKeyFileName);
	// Client key and certificate are sent to server
	final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
	keyStore.load(null, null);
	keyStore.setCertificateEntry("certificate", clientCertificate);
	keyStore.setKeyEntry("private-key", privateKey, 
		clientKeyPassword.toCharArray(),
		new Certificate[] { clientCertificate });
	final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	keyManagerFactory.init(keyStore, clientKeyPassword.toCharArray());
	
	return keyManagerFactory;
}
 
開發者ID:PacktPublishing,項目名稱:MQTT-Essentials-A-Lightweight-IoT-Protocol,代碼行數:22,代碼來源:SecurityHelper.java

示例2: translateSpoiledKey

import java.security.spec.InvalidKeySpecException; //導入依賴的package包/類
/**
 * The test case scenario implemented in the method: - create my own secret
 * Key2 as an instance of a class implements PBEKey - spoil the key (set
 * iteration count to 0, for example) - try to translate key -
 * InvalidKeyException is expected.
 *
 * @return true if InvalidKeyException occurred; false - otherwise.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public boolean translateSpoiledKey() throws NoSuchAlgorithmException,
        InvalidKeySpecException {
    // derive the key
    SecretKey key1 = getMyOwnSecretKey();

    // spoil the key
    ((MyPBKDF2SecretKey) key1).spoil();

    // translate key
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToTest);
    try {
        SecretKey key2 = skf.translateKey(key1);
    } catch (InvalidKeyException ike) {
        // this is expected
        return true;
    }

    return false;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:30,代碼來源:PBKDF2Translate.java

示例3: loadPrivateKey

import java.security.spec.InvalidKeySpecException; //導入依賴的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

示例4: decodePublicKey

import java.security.spec.InvalidKeySpecException; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:SkidJava,項目名稱:BaseClient,代碼行數:24,代碼來源:CryptManager.java

示例5: onEnable

import java.security.spec.InvalidKeySpecException; //導入依賴的package包/類
@Override
public void onEnable() {
    instance = this;

    try {
        mojangPublicKey = KeyFactory.getInstance("EC").generatePublic(
                new X509EncodedKeySpec(Base64
                        .getDecoder()
                        .decode("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8ELkixyLcwlZryUQcu1TvPOmI2B7vX83ndnWRUaXm74wFfa5f/lwQNTfrLVHa2PmenpGI6JhIMUJaWZrjmMj90NoKNFSNBuKdm8rYiXsfaz3K36x/1U26HpG0ZxK/V1V")
                )
        );
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        e.printStackTrace();
    }

    networkManager = new NetworkManager();
}
 
開發者ID:KernelFreeze,項目名稱:BedrockProxy,代碼行數:18,代碼來源:BedrockProxy.java

示例6: verify

import java.security.spec.InvalidKeySpecException; //導入依賴的package包/類
/**
 * 
 * if has performance problem ,change Signature to ThreadLocal instance  
 * @param publicKey public key after base64 encode 
 * @param sign 簽名
 * @param content original content 
 * @return verify result
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
public static boolean verify(String publicKey, String sign, String content)
    throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
  if (null == kf) {
    throw new NoSuchAlgorithmException(RSA_ALG + " KeyFactory not available");
  }
  byte[] bytes = decoder.decode(publicKey);
  X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
  PublicKey pubKey = kf.generatePublic(keySpec);
  Signature signature = Signature.getInstance(SIGN_ALG);
  signature.initVerify(pubKey);
  signature.update(content.getBytes());
  return signature.verify(decoder.decode(sign));
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:26,代碼來源:RSAUtils.java

示例7: testRSAAuthenticationToken

import java.security.spec.InvalidKeySpecException; //導入依賴的package包/類
@Test
public void testRSAAuthenticationToken()
    throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException {
  String tokenstr =
      "[email protected][email protected]@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwg[email protected]WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk=";
  RSAAuthenticationToken token = RSAAuthenticationToken.fromStr(tokenstr);
  String contents = token.plainToken();
  Assert.assertEquals(
      "[email protected][email protected]@9t0tp8ce80SUM5ts6iRGjFJMvCdQ7uvhpyh0RM7smKm3p4wYOrojr4oT1Pnwx7xwgcgEFbQdwPJxIMfivpQ1rHGqiLp67cjACvJ3Ke39pmeAVhybsLADfid6oSjscFaJ",
      contents);
  String sign = token.getSign();
  Assert.assertEquals(
      "WBYouF6hXYrXzBA31HC3VX8Bw9PNgJUtVqOPAaeW9ye3q/D7WWb0M+XMouBIWxWY6v9Un1dGu5Rkjlx6gZbnlHkb2VO8qFR3Y6lppooWCirzpvEBRjlJQu8LPBur0BCfYGq8XYrEZA2NU6sg2zXieqCSiX6BnMnBHNn4cR9iZpk=",
      sign);
  String pubKey =
      "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxKl5TNUTec7fL2degQcCk6vKf3c0wsfNK5V6elKzjWxm0MwbRj/UeR20VSnicBmVIOWrBS9LiERPPvjmmWUOSS2vxwr5XfhBhZ07gCAUNxBOTzgMo5nE45DhhZu5Jzt5qSV6o10Kq7+fCCBlDZ1UoWxZceHkUt5AxcrhEDulFjQIDAQAB";
  Assert.assertTrue(RSAUtils.verify(pubKey, sign, contents));
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:19,代碼來源:TestRSAAuthenticationToken.java

示例8: createPublicKey

import java.security.spec.InvalidKeySpecException; //導入依賴的package包/類
/**
 * 從hex string生成公鑰
 * 
 * @param stringN
 * @param stringE
 * @return 構造好的公鑰
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PublicKey createPublicKey(String stringN, String stringE)
		throws NoSuchAlgorithmException, InvalidKeySpecException {
	try {
		BigInteger N = new BigInteger(stringN, 16); // hex base
		BigInteger E = new BigInteger(stringE, 16); // hex base

		RSAPublicKeySpec spec = new RSAPublicKeySpec(N, E);
		KeyFactory kf = KeyFactory.getInstance("RSA");
		return kf.generatePublic(spec);
	} catch (Exception e) {
		e.printStackTrace();
	}

	return null;
}
 
開發者ID:mugua2015,項目名稱:VerifySignedJar,代碼行數:25,代碼來源:VerfiyPKCS7Info.java

示例9: createKeyPairFromEncodedKeys

import java.security.spec.InvalidKeySpecException; //導入依賴的package包/類
/**
 * Convert encoded private and public keys (bytes) to Private / PublicKey
 * interfaces and generate a KeyPair from them in order to construct a
 * Wallet object in the signIn method<br>
 * <b>Two different encoding</b>
 *
 * @param publicKeyBytes the public key with encoding X509
 * @param privateKeyBytes the private key with encoding PKCS8
 * @return the key pair
 */
public static KeyPair createKeyPairFromEncodedKeys(byte[] publicKeyBytes, byte[] privateKeyBytes) {
    // Generate specs
    final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
    final PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
    
    try {
        // Create PublicKey and PrivateKey interfaces using the factory
        final PrivateKey privateKey = dsaKeyFactory.generatePrivate(privateKeySpec);
        final PublicKey publicKey = dsaKeyFactory.generatePublic(publicKeySpec);
        
        return new KeyPair(publicKey, privateKey);
    } catch (InvalidKeySpecException ex) {
        logAndAbort("Unable to create key pair. Abort!", ex);
    }
    return null;
}
 
開發者ID:StanIsAdmin,項目名稱:CrashCoin,代碼行數:27,代碼來源:Cryptography.java

示例10: rsaSign

import java.security.spec.InvalidKeySpecException; //導入依賴的package包/類
public static String rsaSign(String content, String privateKey,
                             String charset) throws AlipayApiException {
    try {
        PrivateKey priKey = getPrivateKeyFromPKCS8(AlipayConstants.SIGN_TYPE_RSA,
            new ByteArrayInputStream(privateKey.getBytes()));

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

        signature.initSign(priKey);

        if (StringUtils.isEmpty(charset)) {
            signature.update(content.getBytes());
        } else {
            signature.update(content.getBytes(charset));
        }

        byte[] signed = signature.sign();

        return new String(Base64.encodeBase64(signed));
    } catch (InvalidKeySpecException ie) {
        throw new AlipayApiException("RSA私鑰格式不正確,請檢查是否正確配置了PKCS8格式的私鑰", ie);
    } catch (Exception e) {
        throw new AlipayApiException("RSAcontent = " + content + "; charset = " + charset, e);
    }
}
 
開發者ID:1991wangliang,項目名稱:pay,代碼行數:27,代碼來源:AlipaySignature.java

示例11: CBCEncrypt

import java.security.spec.InvalidKeySpecException; //導入依賴的package包/類
public static String CBCEncrypt(int alg, int KeySize, String inFile, String pwd, String mode) throws NoSuchAlgorithmException, InvalidKeySpecException, DataLengthException, IllegalStateException, InvalidCipherTextException, IOException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException
{
	String res = "";
	
	byte[] plain = loadFile(inFile);
	
	Encryptor enc = new Encryptor();
	enc.setParameters(KeySize, alg);
	enc.setEncParameters(alg, pwd, KeySize, mode);
	byte[] bytesRes = enc.CBCEncrypt(plain, alg);
	
	save2File(inFile + ".enc", bytesRes);
	
	res = "Done! file contents encrypted and saved to a corresponding enc file!"; 
	return res;
}
 
開發者ID:MonroCoury,項目名稱:CryptoKnight,代碼行數:17,代碼來源:FileEncrypt.java

示例12: engineGenerateSecret

import java.security.spec.InvalidKeySpecException; //導入依賴的package包/類
/**
 * Generates a <code>SecretKey</code> object from the provided key
 * specification (key material).
 *
 * @param keySpec the specification (key material) of the secret key
 *
 * @return the secret key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a public key.
 */
protected SecretKey engineGenerateSecret(KeySpec keySpec)
    throws InvalidKeySpecException {

    try {
        if (keySpec instanceof DESKeySpec) {
            return new DESKey(((DESKeySpec)keySpec).getKey());
        }

        if (keySpec instanceof SecretKeySpec) {
            return new DESKey(((SecretKeySpec)keySpec).getEncoded());
        }

        throw new InvalidKeySpecException(
                "Inappropriate key specification");

    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException(e.getMessage());
    }
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:31,代碼來源:DESKeyFactory.java

示例13: main

import java.security.spec.InvalidKeySpecException; //導入依賴的package包/類
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
    // TODO This code is demo as the passphrase is hardcoded.
    SystemInfo info = new SystemInfo();
    String salt = info.getHardware().getProcessor().getProcessorID() + info.getOperatingSystem().getFileSystem().getFileStores()[0].getUUID();

    String passPhrase = "Rudy";

    // PBKDF2WithHmacSHA1 available on Java 7 and Java 8. Must match value used on LocalSecretFactory.
    // TODO possible usage scenario. using theis local secret, the end user can create the OfflineToken with a Web application (where he needs to authenticate himself
    // in order to create a correct OfflineToken instance for the user.
    byte[] secret = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(
            new PBEKeySpec(passPhrase.toCharArray(), salt.getBytes(), 1024, 256)).getEncoded();

    String secret64 = Base64Codec.encodeToString(secret, true);
    System.out.println("Local secret value is " + secret64);

}
 
開發者ID:atbashEE,項目名稱:atbash-octopus,代碼行數:18,代碼來源:LocalSecret.java

示例14: validatePassword

import java.security.spec.InvalidKeySpecException; //導入依賴的package包/類
/**
 * Validates a password using a hash.
 *
 * @param   password        the password to check
 * @param   correctHash     the hash of the valid password
 * @return                  true if the password is correct, false if not
 */
public static boolean validatePassword(char[] password, String correctHash)
    throws NoSuchAlgorithmException, InvalidKeySpecException
{
    // Decode the hash into its parameters
    String[] params = correctHash.split(":");
    int iterations = Integer.parseInt(params[ITERATION_INDEX]);
    byte[] salt = fromHex(params[SALT_INDEX]);
    byte[] hash = fromHex(params[PBKDF2_INDEX]);
    // Compute the hash of the provided password, using the same salt,
    // iteration count, and hash length
    byte[] testHash = pbkdf2(password, salt, iterations, hash.length);
    // Compare the hashes in constant time. The password is correct if
    // both hashes match.
    return slowEquals(hash, testHash);
}
 
開發者ID:mit-cml,項目名稱:appinventor-extensions,代碼行數:23,代碼來源:PasswordHash.java

示例15: hash

import java.security.spec.InvalidKeySpecException; //導入依賴的package包/類
/**
 * This method will hash the password and salt combination. Be careful, this method will erase the password after hashed it.
 * You must be sure that you do not need it after using this method.
 *
 * @param password the password who needs to be hashed
 * @param salt     some list of <code>byte</code> which will be included in the password
 * @return a hash of the password and salting combination.
 */
public static byte[] hash(char[] password, byte[] salt) {
    final PBEKeySpec spec = new PBEKeySpec(password, salt, SecurityUtils.ITERATIONS, SecurityUtils.KEY_LENGTH);

    try {
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SecurityUtils.ALGORITHM);
        SecretKey key = secretKeyFactory.generateSecret(spec);
        return key.getEncoded();
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        LOGGER.debug(e.getMessage(), e);
        throw new SecurityException(e);
    } finally {
        // erase the password in the char array in order to not retrieve it in the java memory
        spec.clearPassword();
    }
}
 
開發者ID:Crunchy-Torch,項目名稱:coddy,代碼行數:24,代碼來源:SecurityUtils.java


注:本文中的java.security.spec.InvalidKeySpecException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。