Search in sources :

Example 41 with Key

use of java.security.Key in project Openfire by igniterealtime.

the class AesEncryptor method cipher.

/**
	 * Symmetric encrypt/decrypt routine.
	 *
	 * @param attribute The value to be converted
	 * @param key The encryption key
	 * @param mode The cipher mode (encrypt or decrypt)
	 * @return The converted attribute, or null if conversion fails
	 */
private byte[] cipher(byte[] attribute, byte[] key, int mode) {
    byte[] result = null;
    try {
        // Create AES encryption key
        Key aesKey = new SecretKeySpec(key, "AES");
        // Create AES Cipher
        Cipher aesCipher = Cipher.getInstance(ALGORITHM);
        // Initialize AES Cipher and convert
        aesCipher.init(mode, aesKey, new IvParameterSpec(INIT_PARM));
        result = aesCipher.doFinal(attribute);
    } catch (Exception e) {
        log.error("AES cipher failed", e);
    }
    return result;
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) Key(java.security.Key)

Example 42 with Key

use of java.security.Key in project hbase by apache.

the class EncryptionUtil method unwrapKey.

/**
   * Helper for {@link #unwrapKey(Configuration, String, byte[])} which automatically uses the
   * configured master and alternative keys, rather than having to specify a key type to unwrap
   * with.
   *
   * The configuration must be set up correctly for key alias resolution.
   *
   * @param conf the current configuration
   * @param keyBytes the key encrypted by master (or alternative) to unwrap
   * @return the key bytes, decrypted
   * @throws IOException if the key cannot be unwrapped
   */
public static Key unwrapKey(Configuration conf, byte[] keyBytes) throws IOException {
    Key key;
    String masterKeyName = conf.get(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY, User.getCurrent().getShortName());
    try {
        // First try the master key
        key = unwrapKey(conf, masterKeyName, keyBytes);
    } catch (KeyException e) {
        // one is configured
        if (LOG.isDebugEnabled()) {
            LOG.debug("Unable to unwrap key with current master key '" + masterKeyName + "'");
        }
        String alternateKeyName = conf.get(HConstants.CRYPTO_MASTERKEY_ALTERNATE_NAME_CONF_KEY);
        if (alternateKeyName != null) {
            try {
                key = unwrapKey(conf, alternateKeyName, keyBytes);
            } catch (KeyException ex) {
                throw new IOException(ex);
            }
        } else {
            throw new IOException(e);
        }
    }
    return key;
}
Also used : IOException(java.io.IOException) Key(java.security.Key) KeyException(java.security.KeyException)

Example 43 with Key

use of java.security.Key in project hbase by apache.

the class TestEncryption method checkTransformSymmetry.

private void checkTransformSymmetry(byte[] keyBytes, byte[] iv, byte[] plaintext) throws Exception {
    LOG.info("checkTransformSymmetry: AES, plaintext length = " + plaintext.length);
    Configuration conf = HBaseConfiguration.create();
    String algorithm = conf.get(HConstants.CRYPTO_KEY_ALGORITHM_CONF_KEY, HConstants.CIPHER_AES);
    Cipher aes = Encryption.getCipher(conf, algorithm);
    Key key = new SecretKeySpec(keyBytes, algorithm);
    Encryptor e = aes.getEncryptor();
    e.setKey(key);
    e.setIv(iv);
    e.reset();
    ByteArrayOutputStream encOut = new ByteArrayOutputStream();
    Encryption.encrypt(encOut, plaintext, 0, plaintext.length, e);
    byte[] encrypted = encOut.toByteArray();
    Decryptor d = aes.getDecryptor();
    d.setKey(key);
    d.setIv(iv);
    d.reset();
    ByteArrayInputStream encIn = new ByteArrayInputStream(encrypted);
    ByteArrayOutputStream decOut = new ByteArrayOutputStream();
    Encryption.decrypt(decOut, encIn, plaintext.length, d);
    byte[] result = decOut.toByteArray();
    assertEquals("Decrypted result has different length than plaintext", result.length, plaintext.length);
    assertTrue("Transformation was not symmetric", Bytes.equals(result, plaintext));
}
Also used : HBaseConfiguration(org.apache.hadoop.hbase.HBaseConfiguration) Configuration(org.apache.hadoop.conf.Configuration) ByteArrayInputStream(java.io.ByteArrayInputStream) SecretKeySpec(javax.crypto.spec.SecretKeySpec) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Key(java.security.Key)

Example 44 with Key

use of java.security.Key in project hbase by apache.

the class TestKeyProvider method testTestProvider.

@Test
public void testTestProvider() {
    Configuration conf = HBaseConfiguration.create();
    conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName());
    KeyProvider provider = Encryption.getKeyProvider(conf);
    assertNotNull("Null returned for provider", provider);
    assertTrue("Provider is not the expected type", provider instanceof KeyProviderForTesting);
    Key key = provider.getKey("foo");
    assertNotNull("Test provider did not return a key as expected", key);
    assertEquals("Test provider did not create a key for AES", key.getAlgorithm(), "AES");
    assertEquals("Test provider did not create a key of adequate length", key.getEncoded().length, AES.KEY_LENGTH);
}
Also used : HBaseConfiguration(org.apache.hadoop.hbase.HBaseConfiguration) Configuration(org.apache.hadoop.conf.Configuration) Key(java.security.Key) Test(org.junit.Test)

Example 45 with Key

use of java.security.Key in project hadoop by apache.

the class TestCredentials method testReadWriteStorage.

@SuppressWarnings("unchecked")
@Test
public <T extends TokenIdentifier> void testReadWriteStorage() throws IOException, NoSuchAlgorithmException {
    // create tokenStorage Object
    Credentials ts = new Credentials();
    Token<T> token1 = new Token();
    Token<T> token2 = new Token();
    Text service1 = new Text("service1");
    Text service2 = new Text("service2");
    Collection<Text> services = new ArrayList<Text>();
    services.add(service1);
    services.add(service2);
    token1.setService(service1);
    token2.setService(service2);
    ts.addToken(new Text("sometoken1"), token1);
    ts.addToken(new Text("sometoken2"), token2);
    // create keys and put it in
    final KeyGenerator kg = KeyGenerator.getInstance(DEFAULT_HMAC_ALGORITHM);
    String alias = "alias";
    Map<Text, byte[]> m = new HashMap<Text, byte[]>(10);
    for (int i = 0; i < 10; i++) {
        Key key = kg.generateKey();
        m.put(new Text(alias + i), key.getEncoded());
        ts.addSecretKey(new Text(alias + i), key.getEncoded());
    }
    // create file to store
    File tmpFileName = new File(tmpDir, "tokenStorageTest");
    DataOutputStream dos = new DataOutputStream(new FileOutputStream(tmpFileName));
    ts.write(dos);
    dos.close();
    // open and read it back
    DataInputStream dis = new DataInputStream(new FileInputStream(tmpFileName));
    ts = new Credentials();
    ts.readFields(dis);
    dis.close();
    // get the tokens and compare the services
    Collection<Token<? extends TokenIdentifier>> list = ts.getAllTokens();
    assertEquals("getAllTokens should return collection of size 2", list.size(), 2);
    boolean foundFirst = false;
    boolean foundSecond = false;
    for (Token<? extends TokenIdentifier> token : list) {
        if (token.getService().equals(service1)) {
            foundFirst = true;
        }
        if (token.getService().equals(service2)) {
            foundSecond = true;
        }
    }
    assertTrue("Tokens for services service1 and service2 must be present", foundFirst && foundSecond);
    // compare secret keys
    int mapLen = m.size();
    assertEquals("wrong number of keys in the Storage", mapLen, ts.numberOfSecretKeys());
    for (Text a : m.keySet()) {
        byte[] kTS = ts.getSecretKey(a);
        byte[] kLocal = m.get(a);
        assertTrue("keys don't match for " + a, WritableComparator.compareBytes(kTS, 0, kTS.length, kLocal, 0, kLocal.length) == 0);
    }
    tmpFileName.delete();
}
Also used : TokenIdentifier(org.apache.hadoop.security.token.TokenIdentifier) HashMap(java.util.HashMap) DataOutputStream(java.io.DataOutputStream) ArrayList(java.util.ArrayList) Token(org.apache.hadoop.security.token.Token) Text(org.apache.hadoop.io.Text) DataInputStream(java.io.DataInputStream) FileInputStream(java.io.FileInputStream) FileOutputStream(java.io.FileOutputStream) KeyGenerator(javax.crypto.KeyGenerator) File(java.io.File) Credentials(org.apache.hadoop.security.Credentials) Key(java.security.Key) Test(org.junit.Test)

Aggregations

Key (java.security.Key)302 PrivateKey (java.security.PrivateKey)112 SecretKey (javax.crypto.SecretKey)83 KeyStore (java.security.KeyStore)64 PublicKey (java.security.PublicKey)62 Cipher (javax.crypto.Cipher)60 X509Certificate (java.security.cert.X509Certificate)57 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)50 Test (org.junit.Test)44 IOException (java.io.IOException)42 ByteArrayInputStream (java.io.ByteArrayInputStream)38 Certificate (java.security.cert.Certificate)36 SecretKeySpec (javax.crypto.spec.SecretKeySpec)36 KeyFactory (java.security.KeyFactory)35 InvalidKeyException (java.security.InvalidKeyException)32 KeyGenerator (javax.crypto.KeyGenerator)32 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)26 KeyStoreException (java.security.KeyStoreException)22 SecureRandom (java.security.SecureRandom)21 IvParameterSpec (javax.crypto.spec.IvParameterSpec)21