Java Code Examples for javax.crypto.Cipher#wrap()

The following examples show how to use javax.crypto.Cipher#wrap() . 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
Source File: RsaUtil.java    From util4j with Apache License 2.0 6 votes vote down vote up
/**
 * 用密钥包裹密钥
 * @param key 
 * @param wrapKey 
 * @return
 */
public byte[] wrapKeyByKey(Key key,Key wrapKey)
{
	try {
   		if(key==null ||wrapKey==null)
   		{
   			return null;
   		}
		Cipher cipher=Cipher.getInstance(algorithm);
		//使用私钥包裹模式
		cipher.init(Cipher.WRAP_MODE,wrapKey);
		return cipher.wrap(key);
	} catch (Exception e) {
		log.error(e.getMessage(),e);
	}
   	return null;
}
 
Example 2
Source File: AES_Crypter.java    From secrecy with Apache License 2.0 6 votes vote down vote up
private void writeVaultHeader(File headerFile, byte[] vaultNonce, byte[] salt,
                              int pbkdf2Iterations, Key aesKey,
                              SecretKey keyFromPassphrase) throws Exception {
    Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE);
    FileOutputStream headerOutputStream = new FileOutputStream(headerFile);

    c.init(Cipher.WRAP_MODE, keyFromPassphrase, new IvParameterSpec(vaultNonce));
    byte[] encryptedAesKey = c.wrap(aesKey);

    VaultHeader.Builder vaultHeaderBuilder = VaultHeader.newBuilder();
    vaultHeaderBuilder.setVersion(VAULT_HEADER_VERSION);
    vaultHeaderBuilder.setSalt(ByteString.copyFrom(salt));
    vaultHeaderBuilder.setVaultIV(ByteString.copyFrom(vaultNonce));
    vaultHeaderBuilder.setPbkdf2Iterations(pbkdf2Iterations);
    vaultHeaderBuilder.setEncryptedAesKey(ByteString.copyFrom(encryptedAesKey));
    vaultHeaderBuilder.build().writeTo(headerOutputStream);
    headerOutputStream.close();
}
 
Example 3
Source File: CertificateGenEncryptUtil.java    From hop with Apache License 2.0 5 votes vote down vote up
public static byte[] encodeKeyForTransmission( Key encodingKey, Key keyToEncode ) throws NoSuchAlgorithmException,
  NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException {
  Cipher cipher = Cipher.getInstance( TRANSMISSION_CIPHER_PARAMS );
  cipher.init( Cipher.WRAP_MODE, encodingKey );
  byte[] encodedKey = cipher.wrap( keyToEncode );
  return encodedKey;
}
 
Example 4
Source File: PKCS12KeyStoreSpi.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
protected byte[] wrapKey(
    String algorithm,
    Key key,
    PKCS12PBEParams pbeParams,
    char[] password)
    throws IOException
{
    PBEKeySpec pbeSpec = new PBEKeySpec(password);
    byte[] out;

    try
    {
        SecretKeyFactory keyFact =  helper.createSecretKeyFactory(algorithm);
        PBEParameterSpec defParams = new PBEParameterSpec(
            pbeParams.getIV(),
            pbeParams.getIterations().intValue());

        Cipher cipher = helper.createCipher(algorithm);

        cipher.init(Cipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), defParams);

        out = cipher.wrap(key);
    }
    catch (Exception e)
    {
        throw new IOException("exception encrypting data - " + e.toString());
    }

    return out;
}
 
Example 5
Source File: KeyWrapper.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void doTest(String provider, String algo) throws Exception {
    SecretKey key;
    SecretKey keyToWrap;

    // init a secret Key
    KeyGenerator kg = KeyGenerator.getInstance(AES, PROVIDER);
    kg.init(KEY_LENGTH);
    key = kg.generateKey();
    keyToWrap = kg.generateKey();

    // initialization
    Cipher cipher = Cipher.getInstance(algo, provider);
    cipher.init(Cipher.WRAP_MODE, key);
    AlgorithmParameters params = cipher.getParameters();

    // wrap the key
    byte[] keyWrapper = cipher.wrap(keyToWrap);
    try {
        // check if we can't wrap it again with the same key/IV
        keyWrapper = cipher.wrap(keyToWrap);
        throw new RuntimeException(
                "FAILED: expected IllegalStateException hasn't "
                        + "been thrown ");
    } catch (IllegalStateException ise) {
        System.out.println(ise.getMessage());
        System.out.println("Expected exception");
    }

    // unwrap the key
    cipher.init(Cipher.UNWRAP_MODE, key, params);
    cipher.unwrap(keyWrapper, algo, Cipher.SECRET_KEY);

    // check if we can unwrap second time
    Key unwrapKey = cipher.unwrap(keyWrapper, algo, Cipher.SECRET_KEY);

    if (!Arrays.equals(keyToWrap.getEncoded(), unwrapKey.getEncoded())) {
        throw new RuntimeException(
                "FAILED: original and unwrapped keys are not equal");
    }
}
 
Example 6
Source File: WrappedRawMaterials.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
public byte[] wrapKey(SecretKey key, String wrappingAlg) throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException {
    if (wrappingKey instanceof DelegatedKey) {
        return ((DelegatedKey)wrappingKey).wrap(key, null, wrappingAlg);
    } else {
        Cipher cipher = Cipher.getInstance(wrappingAlg);
        cipher.init(Cipher.WRAP_MODE, wrappingKey, Utils.getRng());
        return cipher.wrap(key);
    }
}
 
Example 7
Source File: TestDelegatedKey.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] wrap(Key key, byte[] additionalAssociatedData, String algorithm) throws InvalidKeyException,
        NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException {
    Cipher cipher = Cipher.getInstance(extractAlgorithm(algorithm));
    cipher.init(Cipher.WRAP_MODE, realKey);
    return cipher.wrap(key);
}
 
Example 8
Source File: WrappedRawMaterials.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
public byte[] wrapKey(SecretKey key, String wrappingAlg) throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException {
    if (wrappingKey instanceof DelegatedKey) {
        return ((DelegatedKey)wrappingKey).wrap(key, null, wrappingAlg);
    } else {
        Cipher cipher = Cipher.getInstance(wrappingAlg);
        cipher.init(Cipher.WRAP_MODE, wrappingKey, Utils.getRng());
        byte[] encryptedKey = cipher.wrap(key);
        return encryptedKey;
    }
}
 
Example 9
Source File: CertificateGenEncryptUtil.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static byte[] encodeKeyForTransmission( Key encodingKey, Key keyToEncode ) throws NoSuchAlgorithmException,
  NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException {
  Cipher cipher = Cipher.getInstance( TRANSMISSION_CIPHER_PARAMS );
  cipher.init( Cipher.WRAP_MODE, encodingKey );
  byte[] encodedKey = cipher.wrap( keyToEncode );
  return encodedKey;
}
 
Example 10
Source File: TestDelegatedKey.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] wrap(Key key, byte[] additionalAssociatedData, String algorithm) throws InvalidKeyException,
        NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException {
    Cipher cipher = Cipher.getInstance(extractAlgorithm(algorithm));
    cipher.init(Cipher.WRAP_MODE, realKey);
    return cipher.wrap(key);
}
 
Example 11
Source File: CryptoUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static byte[] wrapSecretKey(Key secretKey,
                                   Key wrapperKey,
                                   KeyProperties keyProps)  throws SecurityException {
    try {
        Cipher c = initCipher(wrapperKey, keyProps, Cipher.WRAP_MODE);
        return c.wrap(secretKey);
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}
 
Example 12
Source File: TestAESWrapOids.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private static void runTest(DataTuple dataTuple, boolean supportedKeyLength)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        NoSuchPaddingException, InvalidKeyException,
        IllegalBlockSizeException {
    Cipher algorithmCipher = Cipher.getInstance(
            dataTuple.algorithm, PROVIDER_NAME);
    Cipher oidCipher = Cipher.getInstance(dataTuple.oid, PROVIDER_NAME);

    if (algorithmCipher == null) {
        throw new RuntimeException(String.format(
                "Test failed: algorithm string %s getInstance failed.%n",
                dataTuple.algorithm));
    }

    if (oidCipher == null) {
        throw new RuntimeException(
                String.format("Test failed: OID %s getInstance failed.%n",
                        dataTuple.oid));
    }

    if (!algorithmCipher.getAlgorithm().equals(
            dataTuple.algorithm)) {
        throw new RuntimeException(String.format(
                "Test failed: algorithm string %s getInstance "
                        + "doesn't generate expected algorithm.%n",
                dataTuple.oid));
    }

    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(dataTuple.keyLength);
    SecretKey key = kg.generateKey();

    // Wrap the key
    algorithmCipher.init(Cipher.WRAP_MODE, key);
    if (!supportedKeyLength) {
        throw new RuntimeException(String.format(
                "The key length %d is not supported, so the initialization"
                        + " of algorithmCipher should fail.%n",
                dataTuple.keyLength));
    }

    // Unwrap the key
    oidCipher.init(Cipher.UNWRAP_MODE, key);
    if (!supportedKeyLength) {
        throw new RuntimeException(String.format(
                "The key length %d is not supported, so the initialization"
                        + " of oidCipher should fail.%n",
                dataTuple.keyLength));
    }

    byte[] keyWrapper = algorithmCipher.wrap(key);
    Key unwrappedKey = oidCipher.unwrap(keyWrapper, "AES",
            Cipher.SECRET_KEY);

    // Comparison
    if (!Arrays.equals(key.getEncoded(), unwrappedKey.getEncoded())) {
        throw new RuntimeException("Key comparison failed");
    }
}
 
Example 13
Source File: TestCipherKeyWrapperPBEKey.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public boolean runTest(Provider p, String algo, PrintStream out)
        throws Exception {

    byte[] salt = new byte[8];
    int ITERATION_COUNT = 1000;
    AlgorithmParameters pbeParams = null;

    String baseAlgo
            = new StringTokenizer(algo, "/").nextToken().toUpperCase();
    boolean isAES = baseAlgo.contains("AES");

    boolean isUnlimited =
        (Cipher.getMaxAllowedKeyLength(algo) == Integer.MAX_VALUE);

    try {
        // Initialization
        new Random().nextBytes(salt);
        AlgorithmParameterSpec aps = new PBEParameterSpec(salt,
                ITERATION_COUNT);
        SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p);
        SecretKey key = skf.generateSecret(new PBEKeySpec(
                "Secret Key".toCharArray()));
        Cipher ci = Cipher.getInstance(algo);
        if (isAES) {
            ci.init(Cipher.WRAP_MODE, key);
            pbeParams = ci.getParameters();
        } else {
            ci.init(Cipher.WRAP_MODE, key, aps);
        }

        byte[] keyWrapper = ci.wrap(key);
        if (isAES) {
            ci.init(Cipher.UNWRAP_MODE, key, pbeParams);
        } else {
            ci.init(Cipher.UNWRAP_MODE, key, aps);
        }

        Key unwrappedKey = ci.unwrap(keyWrapper, algo, Cipher.SECRET_KEY);

        if ((baseAlgo.endsWith("TRIPLEDES")
                || baseAlgo.endsWith("AES_256")) && !isUnlimited) {
            out.print(
                    "Expected InvalidKeyException not thrown");
            return false;
        }

        return (Arrays.equals(key.getEncoded(), unwrappedKey.getEncoded()));

    } catch (InvalidKeyException ex) {

        if ((baseAlgo.endsWith("TRIPLEDES")
                || baseAlgo.endsWith("AES_256")) && !isUnlimited) {
            out.print(
                    "Expected InvalidKeyException thrown");
            return true;
        } else {
            throw ex;
        }
    }
}
 
Example 14
Source File: XMLCipher.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Encrypts a key to an EncryptedKey structure
 *
 * @param doc the Context document that will be used to general DOM
 * @param key Key to encrypt (will use previously set KEK to
 * perform encryption
 * @param mgfAlgorithm The xenc11 MGF Algorithm to use
 * @param oaepParams The OAEPParams to use
 * @return the <code>EncryptedKey</code>
 * @throws XMLEncryptionException
 */
public EncryptedKey encryptKey(
    Document doc,
    Key key,
    String mgfAlgorithm,
    byte[] oaepParams
) throws XMLEncryptionException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Encrypting key ...");
    }

    if (null == key) {
        log.log(java.util.logging.Level.SEVERE, "Key unexpectedly null...");
    }
    if (cipherMode != WRAP_MODE) {
        log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE...");
    }
    if (algorithm == null) {
        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
    }

    contextDocument = doc;

    byte[] encryptedBytes = null;
    Cipher c;

    if (contextCipher == null) {
        // Now create the working cipher
        c = constructCipher(algorithm, null);
    } else {
        c = contextCipher;
    }
    // Now perform the encryption

    try {
        // Should internally generate an IV
        // todo - allow user to set an IV
        OAEPParameterSpec oaepParameters =
            constructOAEPParameters(
                algorithm, digestAlg, mgfAlgorithm, oaepParams
            );
        if (oaepParameters == null) {
            c.init(Cipher.WRAP_MODE, this.key);
        } else {
            c.init(Cipher.WRAP_MODE, this.key, oaepParameters);
        }
        encryptedBytes = c.wrap(key);
    } catch (InvalidKeyException ike) {
        throw new XMLEncryptionException("empty", ike);
    } catch (IllegalBlockSizeException ibse) {
        throw new XMLEncryptionException("empty", ibse);
    } catch (InvalidAlgorithmParameterException e) {
        throw new XMLEncryptionException("empty", e);
    }

    String base64EncodedEncryptedOctets = Base64.encode(encryptedBytes);
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Encrypted key octets:\n" + base64EncodedEncryptedOctets);
        log.log(java.util.logging.Level.FINE, "Encrypted key octets length = " + base64EncodedEncryptedOctets.length());
    }

    CipherValue cv = ek.getCipherData().getCipherValue();
    cv.setValue(base64EncodedEncryptedOctets);

    try {
        EncryptionMethod method = factory.newEncryptionMethod(new URI(algorithm).toString());
        method.setDigestAlgorithm(digestAlg);
        method.setMGFAlgorithm(mgfAlgorithm);
        method.setOAEPparams(oaepParams);
        ek.setEncryptionMethod(method);
    } catch (URISyntaxException ex) {
        throw new XMLEncryptionException("empty", ex);
    }
    return ek;
}
 
Example 15
Source File: XMLCipher.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
/**
 * Encrypts a key to an EncryptedKey structure
 *
 * @param doc the Context document that will be used to general DOM
 * @param key Key to encrypt (will use previously set KEK to
 * perform encryption
 * @param mgfAlgorithm The xenc11 MGF Algorithm to use
 * @param oaepParams The OAEPParams to use
 * @return the <code>EncryptedKey</code>
 * @throws XMLEncryptionException
 */
public EncryptedKey encryptKey(
    Document doc,
    Key key,
    String mgfAlgorithm,
    byte[] oaepParams
) throws XMLEncryptionException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Encrypting key ...");
    }

    if (null == key) {
        log.log(java.util.logging.Level.SEVERE, "Key unexpectedly null...");
    }
    if (cipherMode != WRAP_MODE) {
        log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE...");
    }
    if (algorithm == null) {
        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
    }

    contextDocument = doc;

    byte[] encryptedBytes = null;
    Cipher c;

    if (contextCipher == null) {
        // Now create the working cipher
        c = constructCipher(algorithm, null);
    } else {
        c = contextCipher;
    }
    // Now perform the encryption

    try {
        // Should internally generate an IV
        // todo - allow user to set an IV
        OAEPParameterSpec oaepParameters =
            constructOAEPParameters(
                algorithm, digestAlg, mgfAlgorithm, oaepParams
            );
        if (oaepParameters == null) {
            c.init(Cipher.WRAP_MODE, this.key);
        } else {
            c.init(Cipher.WRAP_MODE, this.key, oaepParameters);
        }
        encryptedBytes = c.wrap(key);
    } catch (InvalidKeyException ike) {
        throw new XMLEncryptionException("empty", ike);
    } catch (IllegalBlockSizeException ibse) {
        throw new XMLEncryptionException("empty", ibse);
    } catch (InvalidAlgorithmParameterException e) {
        throw new XMLEncryptionException("empty", e);
    }

    String base64EncodedEncryptedOctets = Base64.encode(encryptedBytes);
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Encrypted key octets:\n" + base64EncodedEncryptedOctets);
        log.log(java.util.logging.Level.FINE, "Encrypted key octets length = " + base64EncodedEncryptedOctets.length());
    }

    CipherValue cv = ek.getCipherData().getCipherValue();
    cv.setValue(base64EncodedEncryptedOctets);

    try {
        EncryptionMethod method = factory.newEncryptionMethod(new URI(algorithm).toString());
        method.setDigestAlgorithm(digestAlg);
        method.setMGFAlgorithm(mgfAlgorithm);
        method.setOAEPparams(oaepParams);
        ek.setEncryptionMethod(method);
    } catch (URISyntaxException ex) {
        throw new XMLEncryptionException("empty", ex);
    }
    return ek;
}
 
Example 16
Source File: XMLCipher.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Encrypts a key to an EncryptedKey structure
 *
 * @param doc the Context document that will be used to general DOM
 * @param key Key to encrypt (will use previously set KEK to
 * perform encryption
 * @param mgfAlgorithm The xenc11 MGF Algorithm to use
 * @param oaepParams The OAEPParams to use
 * @return the <code>EncryptedKey</code>
 * @throws XMLEncryptionException
 */
public EncryptedKey encryptKey(
    Document doc,
    Key key,
    String mgfAlgorithm,
    byte[] oaepParams
) throws XMLEncryptionException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Encrypting key ...");
    }

    if (null == key) {
        log.log(java.util.logging.Level.SEVERE, "Key unexpectedly null...");
    }
    if (cipherMode != WRAP_MODE) {
        log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in WRAP_MODE...");
    }
    if (algorithm == null) {
        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
    }

    contextDocument = doc;

    byte[] encryptedBytes = null;
    Cipher c;

    if (contextCipher == null) {
        // Now create the working cipher
        c = constructCipher(algorithm, null);
    } else {
        c = contextCipher;
    }
    // Now perform the encryption

    try {
        // Should internally generate an IV
        // todo - allow user to set an IV
        OAEPParameterSpec oaepParameters =
            constructOAEPParameters(
                algorithm, digestAlg, mgfAlgorithm, oaepParams
            );
        if (oaepParameters == null) {
            c.init(Cipher.WRAP_MODE, this.key);
        } else {
            c.init(Cipher.WRAP_MODE, this.key, oaepParameters);
        }
        encryptedBytes = c.wrap(key);
    } catch (InvalidKeyException ike) {
        throw new XMLEncryptionException("empty", ike);
    } catch (IllegalBlockSizeException ibse) {
        throw new XMLEncryptionException("empty", ibse);
    } catch (InvalidAlgorithmParameterException e) {
        throw new XMLEncryptionException("empty", e);
    }

    String base64EncodedEncryptedOctets = Base64.encode(encryptedBytes);
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Encrypted key octets:\n" + base64EncodedEncryptedOctets);
        log.log(java.util.logging.Level.FINE, "Encrypted key octets length = " + base64EncodedEncryptedOctets.length());
    }

    CipherValue cv = ek.getCipherData().getCipherValue();
    cv.setValue(base64EncodedEncryptedOctets);

    try {
        EncryptionMethod method = factory.newEncryptionMethod(new URI(algorithm).toString());
        method.setDigestAlgorithm(digestAlg);
        method.setMGFAlgorithm(mgfAlgorithm);
        method.setOAEPparams(oaepParams);
        ek.setEncryptionMethod(method);
    } catch (URISyntaxException ex) {
        throw new XMLEncryptionException("empty", ex);
    }
    return ek;
}
 
Example 17
Source File: TestCipherKeyWrapperPBEKey.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public boolean runTest(Provider p, String algo, PrintStream out)
        throws Exception {

    byte[] salt = new byte[8];
    int ITERATION_COUNT = 1000;
    AlgorithmParameters pbeParams = null;

    String baseAlgo
            = new StringTokenizer(algo, "/").nextToken().toUpperCase();
    boolean isAES = baseAlgo.contains("AES");

    try {
        // Initialization
        new Random().nextBytes(salt);
        AlgorithmParameterSpec aps = new PBEParameterSpec(salt,
                ITERATION_COUNT);
        SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p);
        SecretKey key = skf.generateSecret(new PBEKeySpec(
                "Secret Key".toCharArray()));
        Cipher ci = Cipher.getInstance(algo);

        if (isAES) {
            ci.init(Cipher.WRAP_MODE, key);
            pbeParams = ci.getParameters();
        } else {
            ci.init(Cipher.WRAP_MODE, key, aps);
        }

        byte[] keyWrapper = ci.wrap(key);
        if (isAES) {
            ci.init(Cipher.UNWRAP_MODE, key, pbeParams);
        } else {
            ci.init(Cipher.UNWRAP_MODE, key, aps);
        }

        Key unwrappedKey = ci.unwrap(keyWrapper, algo, Cipher.SECRET_KEY);

        if (baseAlgo.endsWith("TRIPLEDES")
                || baseAlgo.endsWith("AES_256")) {
            out.print(
                    "InvalidKeyException not thrown when keyStrength > 128");
            return false;
        }

        return (Arrays.equals(key.getEncoded(), unwrappedKey.getEncoded()));

    } catch (InvalidKeyException ex) {

        if ((baseAlgo.endsWith("TRIPLEDES")
                || baseAlgo.endsWith("AES_256"))) {
            out.println("Expected InvalidKeyException, keyStrength > 128");
            return true;
        } else {
            throw ex;
        }
    }
}
 
Example 18
Source File: TestCipherKeyWrapperPBEKey.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public boolean runTest(Provider p, String algo, PrintStream out)
        throws Exception {

    byte[] salt = new byte[8];
    int ITERATION_COUNT = 1000;
    AlgorithmParameters pbeParams = null;

    String baseAlgo
            = new StringTokenizer(algo, "/").nextToken().toUpperCase();
    boolean isAES = baseAlgo.contains("AES");

    boolean isUnlimited =
        (Cipher.getMaxAllowedKeyLength(algo) == Integer.MAX_VALUE);

    try {
        // Initialization
        new Random().nextBytes(salt);
        AlgorithmParameterSpec aps = new PBEParameterSpec(salt,
                ITERATION_COUNT);
        SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p);
        SecretKey key = skf.generateSecret(new PBEKeySpec(
                "Secret Key".toCharArray()));
        Cipher ci = Cipher.getInstance(algo);
        if (isAES) {
            ci.init(Cipher.WRAP_MODE, key);
            pbeParams = ci.getParameters();
        } else {
            ci.init(Cipher.WRAP_MODE, key, aps);
        }

        byte[] keyWrapper = ci.wrap(key);
        if (isAES) {
            ci.init(Cipher.UNWRAP_MODE, key, pbeParams);
        } else {
            ci.init(Cipher.UNWRAP_MODE, key, aps);
        }

        Key unwrappedKey = ci.unwrap(keyWrapper, algo, Cipher.SECRET_KEY);

        if ((baseAlgo.endsWith("TRIPLEDES")
                || baseAlgo.endsWith("AES_256")) && !isUnlimited) {
            out.print(
                    "Expected InvalidKeyException not thrown");
            return false;
        }

        return (Arrays.equals(key.getEncoded(), unwrappedKey.getEncoded()));

    } catch (InvalidKeyException ex) {

        if ((baseAlgo.endsWith("TRIPLEDES")
                || baseAlgo.endsWith("AES_256")) && !isUnlimited) {
            out.print(
                    "Expected InvalidKeyException thrown");
            return true;
        } else {
            throw ex;
        }
    }
}
 
Example 19
Source File: ContentCryptoMaterial.java    From markdown-image-kit with MIT License 4 votes vote down vote up
/**
 * Secure the given CEK. Note network calls are involved if the CEK is to be protected by KMS.
 *
 * @param cek content encrypting key to be secured
 * @param materials used to provide the key-encryption-key (KEK); or if it is KMS-enabled, the
 *        customer master key id and material description.
 * @param contentCryptoScheme the content crypto scheme
 * @param p optional security provider; can be null if the default is used.
 * @return a secured CEK in the form of ciphertext or ciphertext blob.
 */
private static SecuredCEK secureCEK(SecretKey cek, EncryptionMaterials materials,
        COSKeyWrapScheme kwScheme, SecureRandom srand, Provider p, QCLOUDKMS kms,
        CosServiceRequest req) {
    final Map<String, String> matdesc;

    if (materials.isKMSEnabled()) {
        matdesc = mergeMaterialDescriptions(materials, req);
        /*
        EncryptRequest encryptRequest = new EncryptRequest()
            .withEncryptionContext(matdesc)
            .withKeyId(materials.getCustomerMasterKeyId())
            .withPlaintext(ByteBuffer.wrap(cek.getEncoded()))
            ;
        encryptRequest
            .withGeneralProgressListener(req.getGeneralProgressListener())
            .withRequestMetricCollector(req.getRequestMetricCollector())
            ;
        EncryptResult encryptResult = kms.encrypt(encryptRequest);
        byte[] keyBlob = copyAllBytesFrom(encryptResult.getCiphertextBlob());
        */
        byte[] keyBlob = null;
        return new KMSSecuredCEK(keyBlob, matdesc);
    } else {
        matdesc = materials.getMaterialsDescription();
    }
    Key kek;
    if (materials.getKeyPair() != null) {
        // Do envelope encryption with public key from key pair
        kek = materials.getKeyPair().getPublic();
    } else {
        // Do envelope encryption with symmetric key
        kek = materials.getSymmetricKey();
    }
    String keyWrapAlgo = kwScheme.getKeyWrapAlgorithm(kek);
    try {
        Cipher cipher = p == null ? Cipher.getInstance(keyWrapAlgo)
                : Cipher.getInstance(keyWrapAlgo, p);
        cipher.init(Cipher.WRAP_MODE, kek, srand);
        return new SecuredCEK(cipher.wrap(cek), keyWrapAlgo, matdesc);
    } catch (Exception e) {
        throw new CosClientException("Unable to encrypt symmetric key", e);
    }
}
 
Example 20
Source File: RSAKeyExchange.java    From openjsse with GNU General Public License v2.0 4 votes vote down vote up
byte[] getEncoded(PublicKey publicKey,
        SecureRandom secureRandom) throws GeneralSecurityException {
    Cipher cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);
    cipher.init(Cipher.WRAP_MODE, publicKey, secureRandom);
    return cipher.wrap(premasterSecret);
}