Search in sources :

Example 36 with Key

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

the class Encryption method encryptWithSubjectKey.

/**
   * Encrypts a block of plaintext with the symmetric key resolved for the given subject
   * @param out ciphertext
   * @param in plaintext
   * @param conf configuration
   * @param cipher the encryption algorithm
   * @param iv the initialization vector, can be null
   * @throws IOException
   */
public static void encryptWithSubjectKey(OutputStream out, InputStream in, String subject, Configuration conf, Cipher cipher, byte[] iv) throws IOException {
    Key key = getSecretKeyForSubject(subject, conf);
    if (key == null) {
        throw new IOException("No key found for subject '" + subject + "'");
    }
    Encryptor e = cipher.getEncryptor();
    e.setKey(key);
    // can be null
    e.setIv(iv);
    encrypt(out, in, e);
}
Also used : IOException(java.io.IOException) Key(java.security.Key)

Example 37 with Key

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

the class HFileReaderImpl method createHFileContext.

protected HFileContext createHFileContext(FSDataInputStreamWrapper fsdis, long fileSize, HFileSystem hfs, Path path, FixedFileTrailer trailer) throws IOException {
    HFileContextBuilder builder = new HFileContextBuilder().withIncludesMvcc(shouldIncludeMemstoreTS()).withHBaseCheckSum(true).withHFileName(this.getName()).withCompression(this.compressAlgo);
    // Check for any key material available
    byte[] keyBytes = trailer.getEncryptionKey();
    if (keyBytes != null) {
        Encryption.Context cryptoContext = Encryption.newContext(conf);
        Key key;
        key = EncryptionUtil.unwrapKey(conf, keyBytes);
        // Use the algorithm the key wants
        Cipher cipher = Encryption.getCipher(conf, key.getAlgorithm());
        if (cipher == null) {
            throw new IOException("Cipher '" + key.getAlgorithm() + "' is not available");
        }
        cryptoContext.setCipher(cipher);
        cryptoContext.setKey(key);
        builder.withEncryptionContext(cryptoContext);
    }
    HFileContext context = builder.build();
    if (LOG.isTraceEnabled()) {
        LOG.trace("Reader" + (path != null ? " for " + path : "") + " initialized with cacheConf: " + cacheConf + " comparator: " + comparator.getClass().getSimpleName() + " fileContext: " + context);
    }
    return context;
}
Also used : Encryption(org.apache.hadoop.hbase.io.crypto.Encryption) Cipher(org.apache.hadoop.hbase.io.crypto.Cipher) IOException(java.io.IOException) Key(java.security.Key)

Example 38 with Key

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

the class Authentication method decrypt.

private String decrypt(String value, String initVector) {
    LOG.debug("IV is {}, IV length is {}", initVector, initVector.length());
    if (StringUtils.isBlank(value) || StringUtils.isBlank(initVector)) {
        LOG.error("String to decode or salt is not provided");
        return StringUtils.EMPTY;
    }
    try {
        IvParameterSpec iv = generateIV(initVector);
        Key key = generateKey();
        Cipher cipher = Cipher.getInstance(CIPHER_MODE);
        cipher.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] decryptedString = Base64.decodeBase64(toBytes(value));
        decryptedString = cipher.doFinal(decryptedString);
        return new String(decryptedString);
    } catch (GeneralSecurityException e) {
        LOG.error("Error when decrypting", e);
        return StringUtils.EMPTY;
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) Key(java.security.Key)

Example 39 with Key

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

the class TestMobCompactor method testMajorCompactionFromAdmin.

@Test(timeout = 300000)
public void testMajorCompactionFromAdmin() throws Exception {
    resetConf();
    int mergeSize = 5000;
    // change the mob compaction merge size
    conf.setLong(MobConstants.MOB_COMPACTION_MERGEABLE_THRESHOLD, mergeSize);
    SecureRandom rng = new SecureRandom();
    byte[] keyBytes = new byte[AES.KEY_LENGTH];
    rng.nextBytes(keyBytes);
    String algorithm = conf.get(HConstants.CRYPTO_KEY_ALGORITHM_CONF_KEY, HConstants.CIPHER_AES);
    Key cfKey = new SecretKeySpec(keyBytes, algorithm);
    byte[] encryptionKey = EncryptionUtil.wrapKey(conf, conf.get(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY, User.getCurrent().getShortName()), cfKey);
    final TableName tableName = TableName.valueOf(name.getMethodName());
    HTableDescriptor desc = new HTableDescriptor(tableName);
    HColumnDescriptor hcd1 = new HColumnDescriptor(family1);
    hcd1.setMobEnabled(true);
    hcd1.setMobThreshold(0);
    hcd1.setEncryptionType(algorithm);
    hcd1.setEncryptionKey(encryptionKey);
    HColumnDescriptor hcd2 = new HColumnDescriptor(family2);
    hcd2.setMobEnabled(true);
    hcd2.setMobThreshold(0);
    desc.addFamily(hcd1);
    desc.addFamily(hcd2);
    admin.createTable(desc, getSplitKeys());
    Table table = conn.getTable(tableName);
    BufferedMutator bufMut = conn.getBufferedMutator(tableName);
    int count = 4;
    // generate mob files
    loadData(admin, bufMut, tableName, count, rowNumPerFile);
    int rowNumPerRegion = count * rowNumPerFile;
    assertEquals("Before deleting: mob rows count", regionNum * rowNumPerRegion, countMobRows(table));
    assertEquals("Before deleting: mob cells count", regionNum * cellNumPerRow * rowNumPerRegion, countMobCells(table));
    assertEquals("Before deleting: mob file count", regionNum * count, countFiles(tableName, true, family1));
    createDelFile(table, tableName, Bytes.toBytes(family1), Bytes.toBytes(qf1));
    assertEquals("Before compaction: mob rows count", regionNum * (rowNumPerRegion - delRowNum), countMobRows(table));
    assertEquals("Before compaction: mob cells count", regionNum * (cellNumPerRow * rowNumPerRegion - delCellNum), countMobCells(table));
    assertEquals("Before compaction: family1 mob file count", regionNum * count, countFiles(tableName, true, family1));
    assertEquals("Before compaction: family2 mob file count", regionNum * count, countFiles(tableName, true, family2));
    assertEquals("Before compaction: family1 del file count", regionNum, countFiles(tableName, false, family1));
    assertEquals("Before compaction: family2 del file count", regionNum, countFiles(tableName, false, family2));
    // do the major mob compaction, it will force all files to compaction
    admin.majorCompact(tableName, hcd1.getName(), CompactType.MOB);
    waitUntilMobCompactionFinished(tableName);
    assertEquals("After compaction: mob rows count", regionNum * (rowNumPerRegion - delRowNum), countMobRows(table));
    assertEquals("After compaction: mob cells count", regionNum * (cellNumPerRow * rowNumPerRegion - delCellNum), countMobCells(table));
    assertEquals("After compaction: family1 mob file count", regionNum, countFiles(tableName, true, family1));
    assertEquals("After compaction: family2 mob file count", regionNum * count, countFiles(tableName, true, family2));
    assertEquals("After compaction: family1 del file count", 0, countFiles(tableName, false, family1));
    assertEquals("After compaction: family2 del file count", regionNum, countFiles(tableName, false, family2));
    Assert.assertTrue(verifyEncryption(tableName, family1));
    table.close();
}
Also used : TableName(org.apache.hadoop.hbase.TableName) Table(org.apache.hadoop.hbase.client.Table) HColumnDescriptor(org.apache.hadoop.hbase.HColumnDescriptor) BufferedMutator(org.apache.hadoop.hbase.client.BufferedMutator) SecretKeySpec(javax.crypto.spec.SecretKeySpec) SecureRandom(java.security.SecureRandom) Key(java.security.Key) HTableDescriptor(org.apache.hadoop.hbase.HTableDescriptor) Test(org.junit.Test)

Example 40 with Key

use of java.security.Key in project jjwt by jwtk.

the class DefaultJwtBuilder method compact.

@Override
public String compact() {
    if (payload == null && Collections.isEmpty(claims)) {
        throw new IllegalStateException("Either 'payload' or 'claims' must be specified.");
    }
    if (payload != null && !Collections.isEmpty(claims)) {
        throw new IllegalStateException("Both 'payload' and 'claims' cannot both be specified. Choose either one.");
    }
    if (key != null && keyBytes != null) {
        throw new IllegalStateException("A key object and key bytes cannot both be specified. Choose either one.");
    }
    Header header = ensureHeader();
    Key key = this.key;
    if (key == null && !Objects.isEmpty(keyBytes)) {
        key = new SecretKeySpec(keyBytes, algorithm.getJcaName());
    }
    JwsHeader jwsHeader;
    if (header instanceof JwsHeader) {
        jwsHeader = (JwsHeader) header;
    } else {
        jwsHeader = new DefaultJwsHeader(header);
    }
    if (key != null) {
        jwsHeader.setAlgorithm(algorithm.getValue());
    } else {
        //no signature - plaintext JWT:
        jwsHeader.setAlgorithm(SignatureAlgorithm.NONE.getValue());
    }
    if (compressionCodec != null) {
        jwsHeader.setCompressionAlgorithm(compressionCodec.getAlgorithmName());
    }
    String base64UrlEncodedHeader = base64UrlEncode(jwsHeader, "Unable to serialize header to json.");
    String base64UrlEncodedBody;
    if (compressionCodec != null) {
        byte[] bytes;
        try {
            bytes = this.payload != null ? payload.getBytes(Strings.UTF_8) : toJson(claims);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Unable to serialize claims object to json.");
        }
        base64UrlEncodedBody = TextCodec.BASE64URL.encode(compressionCodec.compress(bytes));
    } else {
        base64UrlEncodedBody = this.payload != null ? TextCodec.BASE64URL.encode(this.payload) : base64UrlEncode(claims, "Unable to serialize claims object to json.");
    }
    String jwt = base64UrlEncodedHeader + JwtParser.SEPARATOR_CHAR + base64UrlEncodedBody;
    if (key != null) {
        //jwt must be signed:
        JwtSigner signer = createSigner(algorithm, key);
        String base64UrlSignature = signer.sign(jwt);
        jwt += JwtParser.SEPARATOR_CHAR + base64UrlSignature;
    } else {
        // no signature (plaintext), but must terminate w/ a period, see
        // https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25#section-6.1
        jwt += JwtParser.SEPARATOR_CHAR;
    }
    return jwt;
}
Also used : JwtSigner(io.jsonwebtoken.impl.crypto.JwtSigner) DefaultJwtSigner(io.jsonwebtoken.impl.crypto.DefaultJwtSigner) Header(io.jsonwebtoken.Header) JwsHeader(io.jsonwebtoken.JwsHeader) SecretKeySpec(javax.crypto.spec.SecretKeySpec) JwsHeader(io.jsonwebtoken.JwsHeader) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Key(java.security.Key)

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