Search in sources :

Example 1 with KeyGenerator

use of javax.crypto.KeyGenerator in project hadoop by apache.

the class MRAppMaster method initJobCredentialsAndUGI.

// end createJob()
/**
   * Obtain the tokens needed by the job and put them in the UGI
   * @param conf
   */
protected void initJobCredentialsAndUGI(Configuration conf) {
    try {
        this.currentUser = UserGroupInformation.getCurrentUser();
        this.jobCredentials = ((JobConf) conf).getCredentials();
        if (CryptoUtils.isEncryptedSpillEnabled(conf)) {
            int keyLen = conf.getInt(MRJobConfig.MR_ENCRYPTED_INTERMEDIATE_DATA_KEY_SIZE_BITS, MRJobConfig.DEFAULT_MR_ENCRYPTED_INTERMEDIATE_DATA_KEY_SIZE_BITS);
            KeyGenerator keyGen = KeyGenerator.getInstance(INTERMEDIATE_DATA_ENCRYPTION_ALGO);
            keyGen.init(keyLen);
            encryptedSpillKey = keyGen.generateKey().getEncoded();
        } else {
            encryptedSpillKey = new byte[] { 0 };
        }
    } catch (IOException e) {
        throw new YarnRuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new YarnRuntimeException(e);
    }
}
Also used : YarnRuntimeException(org.apache.hadoop.yarn.exceptions.YarnRuntimeException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyGenerator(javax.crypto.KeyGenerator)

Example 2 with KeyGenerator

use of javax.crypto.KeyGenerator 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)

Example 3 with KeyGenerator

use of javax.crypto.KeyGenerator in project sonarqube by SonarSource.

the class AesCipher method generateRandomSecretKey.

String generateRandomSecretKey() {
    try {
        KeyGenerator keyGen = KeyGenerator.getInstance(CRYPTO_KEY);
        keyGen.init(KEY_SIZE_IN_BITS, new SecureRandom());
        SecretKey secretKey = keyGen.generateKey();
        return Base64.encodeBase64String(secretKey.getEncoded());
    } catch (Exception e) {
        throw new IllegalStateException("Fail to generate secret key", e);
    }
}
Also used : SecretKey(javax.crypto.SecretKey) SecureRandom(java.security.SecureRandom) KeyGenerator(javax.crypto.KeyGenerator) IOException(java.io.IOException)

Example 4 with KeyGenerator

use of javax.crypto.KeyGenerator in project android_frameworks_base by ResurrectionRemix.

the class SystemKeyStore method generateNewKey.

public byte[] generateNewKey(int numBits, String algName, String keyName) throws NoSuchAlgorithmException {
    // Check if key with similar name exists. If so, return null.
    File keyFile = getKeyFile(keyName);
    if (keyFile.exists()) {
        throw new IllegalArgumentException();
    }
    KeyGenerator skg = KeyGenerator.getInstance(algName);
    SecureRandom srng = SecureRandom.getInstance("SHA1PRNG");
    skg.init(numBits, srng);
    SecretKey sk = skg.generateKey();
    byte[] retKey = sk.getEncoded();
    try {
        // Store the key
        if (!keyFile.createNewFile()) {
            throw new IllegalArgumentException();
        }
        FileOutputStream fos = new FileOutputStream(keyFile);
        fos.write(retKey);
        fos.flush();
        FileUtils.sync(fos);
        fos.close();
        FileUtils.setPermissions(keyFile.getName(), (FileUtils.S_IRUSR | FileUtils.S_IWUSR), -1, -1);
    } catch (IOException ioe) {
        return null;
    }
    return retKey;
}
Also used : SecretKey(javax.crypto.SecretKey) FileOutputStream(java.io.FileOutputStream) SecureRandom(java.security.SecureRandom) IOException(java.io.IOException) File(java.io.File) KeyGenerator(javax.crypto.KeyGenerator)

Example 5 with KeyGenerator

use of javax.crypto.KeyGenerator in project OpenAM by OpenRock.

the class DataEncryptor method encryptWithAsymmetricKey.

/**
     * Encrypts the given data with an asymmetric key. The asymmetric 
     * encryption uses symmetric secret key for data encryption and sends
     * the secret key to the recipient by encrypting the same with given
     * transport key (publick key). 
     * @param data the data to be encrypted.
     * @param encryptionAlgorithm the encryption algorithm to be used.
     *        The encryption algorithm must be one of the supported
     *        algorithm by the underlying JCE encryption provider.
     *        Examples of encryption algorithms are "DES", "AES" etc. 
     * @param encryptionStrength the encryption strength for a given
     *                           encryption algorithm.
     * @param encKey the encryption key to be used. For PKI, this
     *               key should be public key of the intended recipient.  
     * @return the encrypted data in Base64 encoded format.
     */
public static String encryptWithAsymmetricKey(String data, String encryptionAlgorithm, int encryptionStrength, Key encKey) throws Exception {
    try {
        KeyGenerator keygen = KeyGenerator.getInstance(encryptionAlgorithm);
        if (encryptionStrength != 0) {
            keygen.init(encryptionStrength);
        }
        SecretKey sKey = keygen.generateKey();
        Cipher cipher = Cipher.getInstance(encryptionAlgorithm);
        cipher.init(Cipher.ENCRYPT_MODE, sKey);
        byte[] encData = cipher.doFinal(data.getBytes("UTF-8"));
        cipher = Cipher.getInstance(encKey.getAlgorithm());
        cipher.init(Cipher.WRAP_MODE, encKey);
        byte[] keyWrap = cipher.wrap(sKey);
        byte[] encDataPad = wrapKeyWithEncryptedData(encData, keyWrap);
        return Base64.encode(encDataPad);
    } catch (NoSuchAlgorithmException nse) {
        throw new Exception(nse.getMessage());
    } catch (NoSuchPaddingException npe) {
        throw new Exception(npe.getMessage());
    } catch (InvalidKeyException ike) {
        throw new Exception(ike.getMessage());
    } catch (UnsupportedEncodingException uae) {
        throw new Exception(uae.getMessage());
    }
}
Also used : SecretKey(javax.crypto.SecretKey) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Cipher(javax.crypto.Cipher) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) KeyGenerator(javax.crypto.KeyGenerator) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

KeyGenerator (javax.crypto.KeyGenerator)464 SecretKey (javax.crypto.SecretKey)343 Test (org.junit.Test)106 ArrayList (java.util.ArrayList)104 SecureRandom (java.security.SecureRandom)99 Document (org.w3c.dom.Document)98 InputStream (java.io.InputStream)95 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)93 ByteArrayOutputStream (java.io.ByteArrayOutputStream)87 NodeList (org.w3c.dom.NodeList)82 Cipher (javax.crypto.Cipher)79 ByteArrayInputStream (java.io.ByteArrayInputStream)75 XMLStreamReader (javax.xml.stream.XMLStreamReader)68 XMLSecurityProperties (org.apache.xml.security.stax.ext.XMLSecurityProperties)68 DocumentBuilder (javax.xml.parsers.DocumentBuilder)62 Key (java.security.Key)58 QName (javax.xml.namespace.QName)47 IOException (java.io.IOException)45 SecurePart (org.apache.xml.security.stax.ext.SecurePart)40 SecretKeySpec (javax.crypto.spec.SecretKeySpec)39