Java Code Examples for javax.crypto.SecretKey#getAlgorithm()

The following examples show how to use javax.crypto.SecretKey#getAlgorithm() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
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;
}
 
Example 2
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;
}
 
Example 3
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");
}
 
Example 4
@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);
}
 
Example 5
/**
 * 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);
	}
}
 
Example 6
Source Project: Iron   File: IronEncryption.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 7
Source Project: Iron   File: AesCbcWithIntegrity.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 8
@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*"));
}
 
Example 9
@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*"));
}
 
Example 10
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");
}
 
Example 11
/**
 * @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;
    }
}
 
Example 12
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;
}
 
Example 13
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));
        }
    }
}
 
Example 14
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));
        }
    }
}
 
Example 15
/**
 * 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));
        }
    }
}
 
Example 16
/**
 * 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());
        }
    }
}
 
Example 17
/**
 * 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;
}
 
Example 18
/**
 * 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;
}