javax.crypto.SecretKey#getAlgorithm ( )源码实例Demo

下面列出了javax.crypto.SecretKey#getAlgorithm ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: lams   文件: BinaryRC4Decryptor.java
protected static Cipher initCipherForBlock(Cipher cipher, int block,
    EncryptionInfo encryptionInfo, SecretKey skey, int encryptMode)
throws GeneralSecurityException {
    EncryptionVerifier ver = encryptionInfo.getVerifier();
    HashAlgorithm hashAlgo = ver.getHashAlgorithm();
    byte blockKey[] = new byte[4];
    LittleEndian.putUInt(blockKey, 0, block);
    byte encKey[] = CryptoFunctions.generateKey(skey.getEncoded(), hashAlgo, blockKey, 16);
    SecretKey key = new SecretKeySpec(encKey, skey.getAlgorithm());
    if (cipher == null) {
        EncryptionHeader em = encryptionInfo.getHeader();
        cipher = CryptoFunctions.getCipher(key, em.getCipherAlgorithm(), null, null, encryptMode);
    } else {
        cipher.init(encryptMode, key);
    }
    return cipher;
}
 
源代码2 项目: lams   文件: CryptoAPIDecryptor.java
protected static Cipher initCipherForBlock(Cipher cipher, int block,
    EncryptionInfo encryptionInfo, SecretKey skey, int encryptMode)
throws GeneralSecurityException {
    EncryptionVerifier ver = encryptionInfo.getVerifier();
    HashAlgorithm hashAlgo = ver.getHashAlgorithm();
    byte blockKey[] = new byte[4];
    LittleEndian.putUInt(blockKey, 0, block);
    MessageDigest hashAlg = CryptoFunctions.getMessageDigest(hashAlgo);
    hashAlg.update(skey.getEncoded());
    byte encKey[] = hashAlg.digest(blockKey);
    EncryptionHeader header = encryptionInfo.getHeader();
    int keyBits = header.getKeySize();
    encKey = CryptoFunctions.getBlock0(encKey, keyBits / 8);
    if (keyBits == 40) {
        encKey = CryptoFunctions.getBlock0(encKey, 16);
    }
    SecretKey key = new SecretKeySpec(encKey, skey.getAlgorithm());
    if (cipher == null) {
        cipher = CryptoFunctions.getCipher(key, header.getCipherAlgorithm(), null, null, encryptMode);
    } else {
        cipher.init(encryptMode, key);
    }
    return cipher;
}
 
源代码3 项目: openjdk-jdk9   文件: TestRSACipherWrap.java
private static void test(KeyPair kp, SecretKey secretKey,
        Cipher wrapCipher, Cipher unwrapCipher)
        throws Exception {
    String algo = secretKey.getAlgorithm();
    wrapCipher.init(Cipher.WRAP_MODE, kp.getPublic());
    byte[] wrappedKey = wrapCipher.wrap(secretKey);
    unwrapCipher.init(Cipher.UNWRAP_MODE, kp.getPrivate());
    Key unwrappedKey =
            unwrapCipher.unwrap(wrappedKey, algo, Cipher.SECRET_KEY);

    System.out.println("Test " + wrapCipher.getProvider().getName() +
            "/" + unwrapCipher.getProvider().getName() + ": ");
    if (!Arrays.equals(secretKey.getEncoded(),
            unwrappedKey.getEncoded())) {
        throw new Exception("Test Failed!");
    }
    System.out.println("Passed");
}
 
源代码4 项目: aws-encryption-sdk-java   文件: JceMasterKey.java
@Override
public DataKey<JceMasterKey> encryptDataKey(final CryptoAlgorithm algorithm,
        final Map<String, String> encryptionContext,
        final DataKey<?> dataKey) {
    final SecretKey key = dataKey.getKey();
    if (!key.getFormat().equals("RAW")) {
        throw new IllegalArgumentException("Can only re-encrypt data keys which are in RAW format, not "
                + dataKey.getKey().getFormat());
    }
    if (!key.getAlgorithm().equalsIgnoreCase(algorithm.getDataKeyAlgo())) {
        throw new IllegalArgumentException("Incorrect key algorithm. Expected " + key.getAlgorithm()
                + " but got " + algorithm.getKeyAlgo());
    }
    EncryptedDataKey encryptedDataKey = jceKeyCipher_.encryptKey(key.getEncoded(), keyId_, providerName_, encryptionContext);
    return new DataKey<>(key, encryptedDataKey.getEncryptedDataKey(), encryptedDataKey.getProviderInformation(), this);
}
 
源代码5 项目: keystore-explorer   文件: SecretKeyUtil.java
/**
 * Get the information about the supplied secret key.
 *
 * @param secretKey
 *            The secret key
 * @return Key information
 */
public static KeyInfo getKeyInfo(SecretKey secretKey) {
	String algorithm = secretKey.getAlgorithm();

	if (algorithm.equals("RC4")) {
		algorithm = "ARC4"; // RC4 is trademarked so we never want to display it
	}

	if (secretKey.getFormat().equals("RAW")) {
		int keySize = secretKey.getEncoded().length * 8;
		return new KeyInfo(SYMMETRIC, algorithm, keySize);
	} else {
		// Key size unknown
		return new KeyInfo(SYMMETRIC, algorithm);
	}
}
 
源代码6 项目: Iron   文件: IronEncryption.java
public static AesCbcWithIntegrity.SecretKeys generateKey() throws GeneralSecurityException {
    fixPrng();
    KeyGenerator keyGen = KeyGenerator.getInstance(CIPHER);
    // No need to provide a SecureRandom or set a seed since that will
    // happen automatically.
    keyGen.init(AES_KEY_LENGTH_BITS);
    SecretKey confidentialityKey = keyGen.generateKey();


    AesCbcWithIntegrity.SecretKeySpec secretKeySpec = new AesCbcWithIntegrity.SecretKeySpec();
    secretKeySpec.algorithm = confidentialityKey.getAlgorithm();
    secretKeySpec.format = confidentialityKey.getFormat();
    secretKeySpec.encoded = confidentialityKey.getEncoded();

    //Now make the HMAC key
    byte[] integrityKeyBytes = randomBytes(HMAC_KEY_LENGTH_BITS / 8);//to get bytes
    AesCbcWithIntegrity.SecretKeySpec integrityKey = new AesCbcWithIntegrity.SecretKeySpec();
    integrityKey.generate(integrityKeyBytes, HMAC_ALGORITHM);
    AesCbcWithIntegrity.SecretKeys secretKeys = new AesCbcWithIntegrity.SecretKeys();
    secretKeys.setConfidentialityKey(secretKeySpec/*confidentialityKey*/);
    secretKeys.setIntegrityKey(integrityKey);
    return secretKeys;
}
 
源代码7 项目: Iron   文件: AesCbcWithIntegrity.java
public static SecretKeys generateKey() throws GeneralSecurityException {
    fixPrng();
    KeyGenerator keyGen = KeyGenerator.getInstance(CIPHER);
    // No need to provide a SecureRandom or set a seed since that will
    // happen automatically.
    keyGen.init(AES_KEY_LENGTH_BITS);
    SecretKey confidentialityKey = keyGen.generateKey();


    SecretKeySpec secretKeySpec = new SecretKeySpec();
    secretKeySpec.algorithm = confidentialityKey.getAlgorithm();
    secretKeySpec.format = confidentialityKey.getFormat();
    secretKeySpec.encoded = confidentialityKey.getEncoded();

    //Now make the HMAC key
    byte[] integrityKeyBytes = randomBytes(HMAC_KEY_LENGTH_BITS / 8);//to get bytes
    SecretKeySpec integrityKey = new SecretKeySpec();
    integrityKey.generate(integrityKeyBytes, HMAC_ALGORITHM);
    SecretKeys secretKeys = new SecretKeys();
    secretKeys.setConfidentialityKey(secretKeySpec/*confidentialityKey*/);
    secretKeys.setIntegrityKey(integrityKey);
    return secretKeys;
}
 
@Test
public void simple() throws GeneralSecurityException {
    DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId);

    EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
    SecretKey encryptionKey = eMat.getEncryptionKey();
    assertNotNull(encryptionKey);
    Key signingKey = eMat.getSigningKey();
    assertNotNull(signingKey);

    DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
    assertEquals(encryptionKey, dMat.getDecryptionKey());
    assertEquals(signingKey, dMat.getVerificationKey());

    String expectedEncAlg = encryptionKey.getAlgorithm() + "/"
            + (encryptionKey.getEncoded().length * 8);
    String expectedSigAlg = signingKey.getAlgorithm() + "/"
            + (signingKey.getEncoded().length * 8);

    Map<String, String> kmsCtx = kms.getSingleEc();
    assertEquals(expectedEncAlg,
            kmsCtx.get("*" + WrappedRawMaterials.CONTENT_KEY_ALGORITHM + "*"));
    assertEquals(expectedSigAlg, kmsCtx.get("*amzn-ddb-sig-alg*"));
}
 
@Test
public void simple() {
    DirectKmsMaterialsProvider prov = new DirectKmsMaterialsProvider(kms, keyId);

    EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
    SecretKey encryptionKey = eMat.getEncryptionKey();
    assertNotNull(encryptionKey);
    Key signingKey = eMat.getSigningKey();
    assertNotNull(signingKey);

    DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
    assertEquals(encryptionKey, dMat.getDecryptionKey());
    assertEquals(signingKey, dMat.getVerificationKey());

    String expectedEncAlg = encryptionKey.getAlgorithm() + "/"
            + (encryptionKey.getEncoded().length * 8);
    String expectedSigAlg = signingKey.getAlgorithm() + "/"
            + (signingKey.getEncoded().length * 8);

    Map<String, String> kmsCtx = kms.getSingleEc();
    assertEquals(expectedEncAlg,
            kmsCtx.get("*" + WrappedRawMaterials.CONTENT_KEY_ALGORITHM + "*"));
    assertEquals(expectedSigAlg, kmsCtx.get("*amzn-ddb-sig-alg*"));
}
 
源代码10 项目: GlobalPlatformPro   文件: GPSession.java
public void putKey(Key key, int version, boolean replace) throws IOException, GPException {
    ByteArrayOutputStream bo = new ByteArrayOutputStream();

    bo.write(version); // Key Version number

    if (key instanceof RSAPublicKey) {
        bo.write(encodeRSAKey((RSAPublicKey) key));
    } else if (key instanceof ECPublicKey) {
        bo.write(encodeECKey((ECPublicKey) key));
    } else if (key instanceof SecretKey) {
        SecretKey sk = (SecretKey) key;
        if (sk.getAlgorithm() == "DESede") {
            // XXX: this is ugly, re-think how to fit it with plaintext keys.
            PlaintextKeys newKey = PlaintextKeys.fromMasterKey(Arrays.copyOf(sk.getEncoded(), 16));
            newKey.scp = GPSecureChannel.SCP02;
            bo.write(encodeKey(cardKeys, newKey, KeyPurpose.DEK));
        } else
            throw new IllegalArgumentException("Only 3DES symmetric keys are supported: " + sk.getAlgorithm());
    }

    CommandAPDU command = new CommandAPDU(CLA_GP, INS_PUT_KEY, replace ? version : 0x00, 0x01, bo.toByteArray(), 256);
    ResponseAPDU response = transmit(command);
    GPException.check(response, "PUT KEY failed");
}
 
/**
 * @param rawKey REQUIRED: Current secret key.
 * @throws InvalidKeyException
 */
private void unsafeInitWithoutKeyExtraction(SecretKey rawKey) throws InvalidKeyException {
    if (!rawKey.getAlgorithm().equals(this.algorithm)) {
        throw new InvalidKeyException(
                "Algorithm for the provided key must match the algorithm for this Hkdf. Expected "
                        + this.algorithm + " but found " + rawKey.getAlgorithm());
    } else {
        this.prk = rawKey;
    }
}
 
源代码12 项目: qpid-broker-j   文件: AESKeyFileEncrypter.java
AESKeyFileEncrypter(SecretKey secretKey)
{
    if(secretKey == null)
    {
        throw new NullPointerException("A non null secret key must be supplied");
    }
    if(!AES_ALGORITHM.equals(secretKey.getAlgorithm()))
    {
        throw new IllegalArgumentException("Provided secret key was for the algorithm: " + secretKey.getAlgorithm()
                                            + "when" + AES_ALGORITHM + "was needed.");
    }
    _secretKey = secretKey;
}
 
private void actualDecryption(Map<String, AttributeValue> itemAttributes,
        Map<String, Set<EncryptionFlags>> attributeFlags, SecretKey encryptionKey,
        Map<String, String> materialDescription) throws GeneralSecurityException {
    final String encryptionMode = encryptionKey != null ?  encryptionKey.getAlgorithm() +
                materialDescription.get(symmetricEncryptionModeHeader) : null;
    Cipher cipher = null;
    int blockSize = -1;

    for (Map.Entry<String, AttributeValue> entry: itemAttributes.entrySet()) {
        Set<EncryptionFlags> flags = attributeFlags.get(entry.getKey());
        if (flags != null && flags.contains(EncryptionFlags.ENCRYPT)) {
            if (!flags.contains(EncryptionFlags.SIGN)) {
                throw new IllegalArgumentException("All encrypted fields must be signed. Bad field: " + entry.getKey());
            }
            ByteBuffer plainText;
            ByteBuffer cipherText = entry.getValue().getB().asReadOnlyBuffer();
            cipherText.rewind();
            if (encryptionKey instanceof DelegatedKey) {
                plainText = ByteBuffer.wrap(((DelegatedKey)encryptionKey).decrypt(toByteArray(cipherText), null, encryptionMode));
            } else {
                if (cipher == null) {
                    blockSize = getBlockSize(encryptionMode);
                    cipher = Cipher.getInstance(encryptionMode);
                }
                byte[] iv = new byte[blockSize];
                cipherText.get(iv);
                cipher.init(Cipher.DECRYPT_MODE, encryptionKey, new IvParameterSpec(iv), Utils.getRng());
                plainText = ByteBuffer.allocate(cipher.getOutputSize(cipherText.remaining()));
                cipher.doFinal(cipherText, plainText);
                plainText.rewind();
            }
            entry.setValue(AttributeValueMarshaller.unmarshall(plainText));
        }
    }
}
 
private void actualDecryption(Map<String, AttributeValue> itemAttributes,
        Map<String, Set<EncryptionFlags>> attributeFlags, SecretKey encryptionKey,
        Map<String, String> materialDescription) throws GeneralSecurityException {
    final String encryptionMode = encryptionKey != null ?  encryptionKey.getAlgorithm() +
                materialDescription.get(symmetricEncryptionModeHeader) : null;
    Cipher cipher = null;
    int blockSize = -1;

    for (Map.Entry<String, AttributeValue> entry: itemAttributes.entrySet()) {
        Set<EncryptionFlags> flags = attributeFlags.get(entry.getKey());
        if (flags != null && flags.contains(EncryptionFlags.ENCRYPT)) {
            if (!flags.contains(EncryptionFlags.SIGN)) {
                throw new IllegalArgumentException("All encrypted fields must be signed. Bad field: " + entry.getKey());
            }
            ByteBuffer plainText;
            ByteBuffer cipherText = entry.getValue().b().asByteBuffer();
            cipherText.rewind();
            if (encryptionKey instanceof DelegatedKey) {
                plainText = ByteBuffer.wrap(((DelegatedKey)encryptionKey).decrypt(toByteArray(cipherText), null, encryptionMode));
            } else {
                if (cipher == null) {
                    blockSize = getBlockSize(encryptionMode);
                    cipher = Cipher.getInstance(encryptionMode);
                }
                byte[] iv = new byte[blockSize];
                cipherText.get(iv);
                cipher.init(Cipher.DECRYPT_MODE, encryptionKey, new IvParameterSpec(iv), Utils.getRng());
                plainText = ByteBuffer.allocate(cipher.getOutputSize(cipherText.remaining()));
                cipher.doFinal(cipherText, plainText);
                plainText.rewind();
            }
            entry.setValue(AttributeValueMarshaller.unmarshall(plainText));
        }
    }
}
 
/**
 * This method has the side effect of replacing the plaintext
 * attribute-values of "itemAttributes" with ciphertext attribute-values
 * (which are always in the form of ByteBuffer) as per the corresponding
 * attribute flags.
 */
private void actualEncryption(Map<String, AttributeValue> itemAttributes,
        Map<String, Set<EncryptionFlags>> attributeFlags,
        Map<String, String> materialDescription,
        SecretKey encryptionKey) throws GeneralSecurityException {
    String encryptionMode = null;
    if (encryptionKey != null) {
        materialDescription.put(this.symmetricEncryptionModeHeader,
                SYMMETRIC_ENCRYPTION_MODE);
        encryptionMode = encryptionKey.getAlgorithm() + SYMMETRIC_ENCRYPTION_MODE;
    }
    Cipher cipher = null;
    int blockSize = -1;

    for (Map.Entry<String, AttributeValue> entry: itemAttributes.entrySet()) {
        Set<EncryptionFlags> flags = attributeFlags.get(entry.getKey());
        if (flags != null && flags.contains(EncryptionFlags.ENCRYPT)) {
            if (!flags.contains(EncryptionFlags.SIGN)) {
                throw new IllegalArgumentException("All encrypted fields must be signed. Bad field: " + entry.getKey());
            }
            ByteBuffer plainText = AttributeValueMarshaller.marshall(entry.getValue());
            plainText.rewind();
            ByteBuffer cipherText;
            if (encryptionKey instanceof DelegatedKey) {
                DelegatedKey dk = (DelegatedKey) encryptionKey;
                cipherText = ByteBuffer.wrap(
                        dk.encrypt(toByteArray(plainText), null, encryptionMode));
            } else {
                if (cipher == null) {
                    blockSize = getBlockSize(encryptionMode);
                    cipher = Cipher.getInstance(encryptionMode);
                }
                // Encryption format: <iv><ciphertext>
                // Note a unique iv is generated per attribute
                cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, Utils.getRng());
                cipherText = ByteBuffer.allocate(blockSize + cipher.getOutputSize(plainText.remaining()));
                cipherText.position(blockSize);
                cipher.doFinal(plainText, cipherText);
                cipherText.flip();
                final byte[] iv = cipher.getIV();
                if (iv.length != blockSize) {
                    throw new IllegalStateException(String.format("Generated IV length (%d) not equal to block size (%d)",
                            iv.length, blockSize));
                }
                cipherText.put(iv);
                cipherText.rewind();
            }
            // Replace the plaintext attribute value with the encrypted content
            entry.setValue(new AttributeValue().withB(cipherText));
        }
    }
}
 
/**
 * This method has the side effect of replacing the plaintext
 * attribute-values of "itemAttributes" with ciphertext attribute-values
 * (which are always in the form of ByteBuffer) as per the corresponding
 * attribute flags.
 */
private void actualEncryption(Map<String, AttributeValue> itemAttributes,
        Map<String, Set<EncryptionFlags>> attributeFlags,
        Map<String, String> materialDescription,
        SecretKey encryptionKey) throws GeneralSecurityException {
    String encryptionMode = null;
    if (encryptionKey != null) {
        materialDescription.put(this.symmetricEncryptionModeHeader,
                SYMMETRIC_ENCRYPTION_MODE);
        encryptionMode = encryptionKey.getAlgorithm() + SYMMETRIC_ENCRYPTION_MODE;
    }
    Cipher cipher = null;
    int blockSize = -1;

    for (Map.Entry<String, AttributeValue> entry: itemAttributes.entrySet()) {
        Set<EncryptionFlags> flags = attributeFlags.get(entry.getKey());
        if (flags != null && flags.contains(EncryptionFlags.ENCRYPT)) {
            if (!flags.contains(EncryptionFlags.SIGN)) {
                throw new IllegalArgumentException("All encrypted fields must be signed. Bad field: " + entry.getKey());
            }
            ByteBuffer plainText = AttributeValueMarshaller.marshall(entry.getValue());
            plainText.rewind();
            ByteBuffer cipherText;
            if (encryptionKey instanceof DelegatedKey) {
                DelegatedKey dk = (DelegatedKey) encryptionKey;
                cipherText = ByteBuffer.wrap(
                        dk.encrypt(toByteArray(plainText), null, encryptionMode));
            } else {
                if (cipher == null) {
                    blockSize = getBlockSize(encryptionMode);
                    cipher = Cipher.getInstance(encryptionMode);
                }
                // Encryption format: <iv><ciphertext>
                // Note a unique iv is generated per attribute
                cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, Utils.getRng());
                cipherText = ByteBuffer.allocate(blockSize + cipher.getOutputSize(plainText.remaining()));
                cipherText.position(blockSize);
                cipher.doFinal(plainText, cipherText);
                cipherText.flip();
                final byte[] iv = cipher.getIV();
                if (iv.length != blockSize) {
                    throw new IllegalStateException(String.format("Generated IV length (%d) not equal to block size (%d)",
                            iv.length, blockSize));
                }
                cipherText.put(iv);
                cipherText.rewind();
            }
            // Replace the plaintext attribute value with the encrypted content
            entry.setValue(AttributeValue.builder().b(SdkBytes.fromByteBuffer(cipherText)).build());
        }
    }
}
 
源代码17 项目: aws-dynamodb-encryption-java   文件: Hkdf.java
/**
 * Initializes this Hkdf to use the provided key directly for creation of
 * new keys. If <code>rawKey</code> is not securely generated and uniformly
 * distributed over the total key-space, then this will result in an
 * insecure key derivation function (KDF). <em>DO NOT USE THIS UNLESS YOU
 * ARE ABSOLUTELY POSITIVE THIS IS THE CORRECT THING TO DO.</em>
 *
 * @param rawKey
 *            the pseudorandom key directly used to derive keys
 * @throws InvalidKeyException
 *             if the algorithm for <code>rawKey</code> does not match the
 *             algorithm this Hkdf was created with
 */
public void unsafeInitWithoutKeyExtraction(final SecretKey rawKey)
        throws InvalidKeyException {
    if (!rawKey.getAlgorithm().equals(algorithm)) {
        throw new InvalidKeyException(
                "Algorithm for the provided key must match the algorithm for this Hkdf. Expected " +
                algorithm + " but found " + rawKey.getAlgorithm());
    }

    this.prk = rawKey;
}
 
源代码18 项目: aws-dynamodb-encryption-java   文件: Hkdf.java
/**
 * Initializes this Hkdf to use the provided key directly for creation of
 * new keys. If <code>rawKey</code> is not securely generated and uniformly
 * distributed over the total key-space, then this will result in an
 * insecure key derivation function (KDF). <em>DO NOT USE THIS UNLESS YOU
 * ARE ABSOLUTELY POSITIVE THIS IS THE CORRECT THING TO DO.</em>
 *
 * @param rawKey
 *            the pseudorandom key directly used to derive keys
 * @throws InvalidKeyException
 *             if the algorithm for <code>rawKey</code> does not match the
 *             algorithm this Hkdf was created with
 */
public void unsafeInitWithoutKeyExtraction(final SecretKey rawKey)
        throws InvalidKeyException {
    if (!rawKey.getAlgorithm().equals(algorithm)) {
        throw new InvalidKeyException(
                "Algorithm for the provided key must match the algorithm for this Hkdf. Expected " +
                algorithm + " but found " + rawKey.getAlgorithm());
    }

    this.prk = rawKey;
}