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


Java KeySpec類代碼示例

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


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

示例1: generateKeyFromPassword

import java.security.spec.KeySpec; //導入依賴的package包/類
/**
 * A function that generates password-based AES & HMAC keys. It prints out exceptions but
 * doesn't throw them since none should be encountered. If they are
 * encountered, the return value is null.
 *
 * @param password The password to derive the keys from.
 * @return The AES & HMAC keys.
 * @throws GeneralSecurityException if AES is not implemented on this system,
 *                                  or a suitable RNG is not available
 */
public static SecretKeys generateKeyFromPassword(String password, byte[] salt) throws GeneralSecurityException {
    fixPrng();
    //Get enough random bytes for both the AES key and the HMAC key:
    KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt,
            PBE_ITERATION_COUNT, AES_KEY_LENGTH_BITS + HMAC_KEY_LENGTH_BITS);
    SecretKeyFactory keyFactory = SecretKeyFactory
            .getInstance(PBE_ALGORITHM);
    byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();

    // Split the random bytes into two parts:
    byte[] confidentialityKeyBytes = copyOfRange(keyBytes, 0, AES_KEY_LENGTH_BITS /8);
    byte[] integrityKeyBytes = copyOfRange(keyBytes, AES_KEY_LENGTH_BITS /8, AES_KEY_LENGTH_BITS /8 + HMAC_KEY_LENGTH_BITS /8);

    //Generate the AES key
    SecretKey confidentialityKey = new SecretKeySpec(confidentialityKeyBytes, CIPHER);

    //Generate the HMAC key
    SecretKey integrityKey = new SecretKeySpec(integrityKeyBytes, HMAC_ALGORITHM);

    return new SecretKeys(confidentialityKey, integrityKey);
}
 
開發者ID:YoeriNijs,項目名稱:NoteBuddy,代碼行數:32,代碼來源:AesCbcWithIntegrity.java

示例2: engineGeneratePublic

import java.security.spec.KeySpec; //導入依賴的package包/類
/**
 * Converts, if possible, a key specification into a
 * {@link BCRainbowPublicKey}. Currently, the following key specifications are
 * supported:{@link X509EncodedKeySpec}.
 * <p/>
 * <p/>
 * <p/>
 * The ASN.1 definition of a public key's structure is
 * <p/>
 * <pre>
 *    RainbowPublicKey ::= SEQUENCE {
 *      oid            OBJECT IDENTIFIER        -- OID identifying the algorithm
 *      docLength      Integer                  -- length of signable msg
 *      coeffquadratic SEQUENCE OF OCTET STRING -- quadratic (mixed) coefficients
 *      coeffsingular  SEQUENCE OF OCTET STRING -- singular coefficients
 *      coeffscalar       OCTET STRING             -- scalar coefficients
 *       }
 * </pre>
 * <p/>
 * <p/>
 *
 * @param keySpec the key specification
 * @return the Rainbow public key
 * @throws InvalidKeySpecException if the KeySpec is not supported.
 */
public PublicKey engineGeneratePublic(KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof RainbowPublicKeySpec)
    {
        return new BCRainbowPublicKey((RainbowPublicKeySpec)keySpec);
    }
    else if (keySpec instanceof X509EncodedKeySpec)
    {
        // get the DER-encoded Key according to X.509 from the spec
        byte[] encKey = ((X509EncodedKeySpec)keySpec).getEncoded();

        // decode the SubjectPublicKeyInfo data structure to the pki object
        try
        {
            return generatePublic(SubjectPublicKeyInfo.getInstance(encKey));
        }
        catch (Exception e)
        {
            throw new InvalidKeySpecException(e.toString());
        }
    }

    throw new InvalidKeySpecException("Unknown key specification: " + keySpec + ".");
}
 
開發者ID:Appdome,項目名稱:ipack,代碼行數:51,代碼來源:RainbowKeyFactorySpi.java

示例3: getECPrivateKey

import java.security.spec.KeySpec; //導入依賴的package包/類
private static PrivateKey getECPrivateKey(String curve) throws Exception {
    String s;
    ECParameterSpec params;
    switch (curve) {
        case "P256":
            s = EC_P256_S;
            params = EC_P256_PARAMS;
            break;
        case "P384":
            s = EC_P384_S;
            params = EC_P384_PARAMS;
            break;
        case "P521":
            s = EC_P521_S;
            params = EC_P521_PARAMS;
            break;
        default:
            throw new Exception("Unsupported curve: " + curve);
    }
    KeyFactory kf = KeyFactory.getInstance("EC");
    KeySpec kspec = new ECPrivateKeySpec(new BigInteger(s), params);
    return kf.generatePrivate(kspec);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:24,代碼來源:GenerationTests.java

示例4: getCipher

import java.security.spec.KeySpec; //導入依賴的package包/類
protected Cipher getCipher(byte[] key, byte[] ivec, int mode)
    throws GeneralSecurityException {
    // NoSuchAlgorithException
    SecretKeyFactory factory = SecretKeyFactory.getInstance("desede");

    // InvalidKeyException
    KeySpec spec = new DESedeKeySpec(key, 0);

    // InvalidKeySpecException
    SecretKey secretKey = factory.generateSecret(spec);

    // IV
    if (ivec == null) {
        ivec = ZERO_IV;
    }

    // NoSuchAlgorithmException, NoSuchPaddingException
    // NoSuchProviderException
    Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
    IvParameterSpec encIv = new IvParameterSpec(ivec, 0, ivec.length);

    // InvalidKeyException, InvalidAlgorithParameterException
    cipher.init(mode, secretKey, encIv);

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

示例5: engineGenerateSecret

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

示例6: engineGeneratePrivate

import java.security.spec.KeySpec; //導入依賴的package包/類
protected PrivateKey engineGeneratePrivate(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof PKCS8EncodedKeySpec)
    {
        try
        {
            PrivateKeyInfo info = PrivateKeyInfo.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded());
            PrivateKey     key = BouncyCastleProvider.getPrivateKey(info);

            if (key != null)
            {
                return key;
            }

            throw new InvalidKeySpecException("no factory found for OID: " + info.getPrivateKeyAlgorithm().getAlgorithm());
        }
        catch (Exception e)
        {
            throw new InvalidKeySpecException(e.toString());
        }
    }

    throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName());
}
 
開發者ID:Appdome,項目名稱:ipack,代碼行數:27,代碼來源:KeyFactory.java

示例7: fill_q

import java.security.spec.KeySpec; //導入依賴的package包/類
/**
 * A method to get 64 random bytes deterministically based on user input
 * And to also fill the queue with numbers
 **/
private void fill_q(char[] sentence, char[] word, String encryption) throws NoSuchAlgorithmException, InvalidKeySpecException {
    // 512 bit key_length (64 bytes). Python and C++ use bytes rather than bits.
    KeySpec ks = new PBEKeySpec(sentence, chars_to_bytes(word), iterations, key_length_in_bytes * 8);
    SecretKeyFactory skf = SecretKeyFactory.getInstance(encryption);

    if (debug) {
        String hex_random_bytes = byte_array_to_hex(skf.generateSecret(ks).getEncoded());
        System.out.println("PBKDF2:  " + hex_random_bytes);
    }

    byte[] random_bytes = skf.generateSecret(ks).getEncoded();

    for (byte b : random_bytes) {
        if (debug) {
            // & 0xFF ensures the int is unsigned
            System.out.println(((int) b) & 0xFF);
        }

        number_queue.add(((int) b) & 0xFF);
    }
}
 
開發者ID:lp1dev,項目名稱:dpg-android,代碼行數:26,代碼來源:dpg.java

示例8: engineGeneratePublic

import java.security.spec.KeySpec; //導入依賴的package包/類
protected PublicKey engineGeneratePublic(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof X509EncodedKeySpec)
    {
        try
        {
            return generatePublic(SubjectPublicKeyInfo.getInstance(((X509EncodedKeySpec)keySpec).getEncoded()));
        }
        catch (Exception e)
        {
            throw new InvalidKeySpecException("encoded key spec not recognised");
        }
    }
    else
    {
        throw new InvalidKeySpecException("key spec not recognised");
    }
}
 
開發者ID:Appdome,項目名稱:ipack,代碼行數:21,代碼來源:BaseKeyFactorySpi.java

示例9: engineGetKeySpec

import java.security.spec.KeySpec; //導入依賴的package包/類
protected KeySpec engineGetKeySpec(
    Key key,
    Class spec)
    throws InvalidKeySpecException
{
    if (spec.isAssignableFrom(PKCS8EncodedKeySpec.class) && key.getFormat().equals("PKCS#8"))
    {
        return new PKCS8EncodedKeySpec(key.getEncoded());
    }
    else if (spec.isAssignableFrom(X509EncodedKeySpec.class) && key.getFormat().equals("X.509"))
    {
        return new X509EncodedKeySpec(key.getEncoded());
    }

    throw new InvalidKeySpecException("not implemented yet " + key + " " + spec);
}
 
開發者ID:Appdome,項目名稱:ipack,代碼行數:17,代碼來源:BaseKeyFactorySpi.java

示例10: AESObfuscator

import java.security.spec.KeySpec; //導入依賴的package包/類
/**
 * @param salt an array of random bytes to use for each (un)obfuscation
 * @param applicationId application identifier, e.g. the package name
 * @param deviceId device identifier. Use as many sources as possible to
 *    create this unique identifier.
 */
public AESObfuscator(byte[] salt, String applicationId, String deviceId) {
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM);
        KeySpec keySpec =
            new PBEKeySpec((applicationId + deviceId).toCharArray(), salt, 1024, 256);
        SecretKey tmp = factory.generateSecret(keySpec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
        mEncryptor = Cipher.getInstance(CIPHER_ALGORITHM);
        mEncryptor.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(IV));
        mDecryptor = Cipher.getInstance(CIPHER_ALGORITHM);
        mDecryptor.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));
    } catch (GeneralSecurityException e) {
        // This can't happen on a compatible Android device.
        throw new RuntimeException("Invalid environment", e);
    }
}
 
開發者ID:snoozinsquatch,項目名稱:unity-obb-downloader,代碼行數:23,代碼來源:AESObfuscator.java

示例11: AESObfuscator

import java.security.spec.KeySpec; //導入依賴的package包/類
/**
 * @param salt an array of random bytes to use for each (un)obfuscation
 * @param applicationId application identifier, e.g. the package name
 * @param deviceId device identifier. Use as many sources as possible to
 *    create this unique identifier.
 */
public AESObfuscator(byte[] salt, String applicationId, String deviceId) {
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM);
        KeySpec keySpec =   
            new PBEKeySpec((applicationId + deviceId).toCharArray(), salt, 1024, 256);
        SecretKey tmp = factory.generateSecret(keySpec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
        mEncryptor = Cipher.getInstance(CIPHER_ALGORITHM);
        mEncryptor.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(IV));
        mDecryptor = Cipher.getInstance(CIPHER_ALGORITHM);
        mDecryptor.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));
    } catch (GeneralSecurityException e) {
        // This can't happen on a compatible Android device.
        throw new RuntimeException("Invalid environment", e);
    }
}
 
開發者ID:tranleduy2000,項目名稱:text_converter,代碼行數:23,代碼來源:AESObfuscator.java

示例12: getEncryptedPassword

import java.security.spec.KeySpec; //導入依賴的package包/類
public String getEncryptedPassword(String password, String salt)
		throws NoSuchAlgorithmException, InvalidKeySpecException {
	// PBKDF2 with SHA-1 as the hashing algorithm. Note that the NIST
	// specifically names SHA-1 as an acceptable hashing algorithm for PBKDF2
	String algorithm = "PBKDF2WithHmacSHA1";
	// SHA-1 generates 160 bit hashes, so that's what makes sense here
	int derivedKeyLength = 160;
	// Pick an iteration count that works for you. The NIST recommends at
	// least 1,000 iterations:
	// http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
	// iOS 4.x reportedly uses 10,000:
	// http://blog.crackpassword.com/2010/09/smartphone-forensics-cracking-blackberry-backup-passwords/
	int iterations = 20000;
	char[] pwd = new String(password).toCharArray();		
	KeySpec spec = new PBEKeySpec(pwd, Base64.getDecoder().decode(salt), iterations, derivedKeyLength);
	SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm);
	byte[] bytes = f.generateSecret(spec).getEncoded();
	return Base64.getEncoder().encodeToString(bytes);
}
 
開發者ID:Angular2Guy,項目名稱:AngularAndSpring,代碼行數:20,代碼來源:PasswordEncryption.java

示例13: engineGetKeySpec

import java.security.spec.KeySpec; //導入依賴的package包/類
/**
 * Returns a specification (key material) of the given key
 * in the requested format.
 *
 * @param key the key
 *
 * @param keySpecCl the requested format in which the key material shall be
 * returned
 *
 * @return the underlying key specification (key material) in the
 * requested format
 *
 * @exception InvalidKeySpecException if the requested key
 * specification is inappropriate for the given key, or the
 * given key cannot be processed (e.g., the given key has an
 * unrecognized algorithm or format).
 */
protected KeySpec engineGetKeySpec(SecretKey key, Class<?> keySpecCl)
    throws InvalidKeySpecException {
    if (key instanceof javax.crypto.interfaces.PBEKey) {
        // Check if requested key spec is amongst the valid ones
        if ((keySpecCl != null)
            && PBEKeySpec.class.isAssignableFrom(keySpecCl)) {
            javax.crypto.interfaces.PBEKey pKey =
                (javax.crypto.interfaces.PBEKey) key;
            return new PBEKeySpec
                (pKey.getPassword(), pKey.getSalt(),
                 pKey.getIterationCount(), pKey.getEncoded().length*8);
        } else {
            throw new InvalidKeySpecException("Invalid key spec");
        }
    } else {
        throw new InvalidKeySpecException("Invalid key " +
                                           "format/algorithm");
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:37,代碼來源:PBKDF2HmacSHA1Factory.java

示例14: getPublicKeyFromPem

import java.security.spec.KeySpec; //導入依賴的package包/類
private PublicKey getPublicKeyFromPem(String pem) 
throws GeneralSecurityException, IOException {

    InputStream stream = new ByteArrayInputStream(
            pem.getBytes("UTF-8"));

    PEMReader reader = new PEMReader(stream);
    byte[] bytes = reader.getDerBytes(); 	
    PublicKey pubKey;

    if (PEMReader.PUBLIC_X509_MARKER.equals(reader.getBeginMarker())) {
        KeySpec keySpec = new X509EncodedKeySpec(bytes);
        KeyFactory fac = KeyFactory.getInstance("RSA");
        pubKey = fac.generatePublic(keySpec);
    } else if (PEMReader.CERTIFICATE_X509_MARKER.equals(reader.getBeginMarker())) {
        pubKey = getPublicKeyFromDerCert(bytes);
    } else {
        throw new IOException("Invalid PEM fileL: Unknown marker for " + 
                " public key or cert " + reader.getBeginMarker());
    }

    return pubKey;
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:24,代碼來源:RSA_SHA1.java

示例15: createPrivateKey

import java.security.spec.KeySpec; //導入依賴的package包/類
public static SigningPrivateKey createPrivateKey(BigInteger x, BigInteger p, BigInteger q, BigInteger g) throws NoSuchAlgorithmException, InvalidKeySpecException {
  if (x == null) {
    throw new IllegalArgumentException("x must not be null");
  }
  if (p == null) {
    throw new IllegalArgumentException("p must not be null");
  }
  if (q == null) {
    throw new IllegalArgumentException("q must not be null");
  }
  if (g == null) {
    throw new IllegalArgumentException("g must not be null");
  }
  KeySpec keySpec = new DSAPrivateKeySpec(x, p, q, g);
  KeyFactory keyFactory = KeyFactory.getInstance("DSA");
  DSAPrivateKey privateKey = (DSAPrivateKey) keyFactory.generatePrivate(keySpec);
  return new DSASigningPrivateKey(privateKey);
}
 
開發者ID:mozilla-mobile,項目名稱:FirefoxData-android,代碼行數:19,代碼來源:DSACryptoImplementation.java


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