当前位置: 首页>>代码示例>>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;未经允许,请勿转载。