Search in sources :

Example 36 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project robovm by robovm.

the class myMac method testUpdateByteBuffer01.

/**
     * Test for <code>update(ByteBuffer input)</code>
     * <code>update(byte[] input, int offset, int len)</code>
     * methods
     * Assertion: processes Mac; if input is null then do nothing
     */
public void testUpdateByteBuffer01() throws NoSuchAlgorithmException, NoSuchProviderException, IllegalArgumentException, IllegalStateException, InvalidAlgorithmParameterException, InvalidKeyException {
    if (!DEFSupported) {
        fail(NotSupportedMsg);
        return;
    }
    Mac[] macs = createMacs();
    assertNotNull("Mac objects were not created", macs);
    byte[] bb = { (byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5 };
    SecretKeySpec sks = new SecretKeySpec(bb, "SHA1");
    ByteBuffer byteNull = null;
    ByteBuffer byteBuff = ByteBuffer.allocate(0);
    byte[] bb1;
    byte[] bb2;
    for (int i = 0; i < macs.length; i++) {
        macs[i].init(sks);
        bb1 = macs[i].doFinal();
        try {
            macs[i].update(byteNull);
            fail("IllegalArgumentException must be thrown because buffer is null");
        } catch (IllegalArgumentException e) {
        }
        macs[i].update(byteBuff);
        bb2 = macs[i].doFinal();
        for (int t = 0; t < bb1.length; t++) {
            assertEquals("Incorrect doFinal result", bb1[t], bb2[t]);
        }
        macs[i].init(sks);
        bb1 = macs[i].doFinal();
        macs[i].update(null, 0, 0);
        bb2 = macs[i].doFinal();
        for (int t = 0; t < bb1.length; t++) {
            assertEquals("Incorrect doFinal result", bb1[t], bb2[t]);
        }
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) ByteBuffer(java.nio.ByteBuffer) Mac(javax.crypto.Mac)

Example 37 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project hbase by apache.

the class TestEncryptionUtil method testKeyWrapping.

// There does not seem to be a ready way to test either getKeyFromBytesOrMasterKey
// or createEncryptionContext, and the existing code under MobUtils appeared to be
// untested.  Not ideal!
@Test
public void testKeyWrapping() throws Exception {
    // set up the key provider for testing to resolve a key for our test subject
    // we don't need HBaseConfiguration for this
    Configuration conf = new Configuration();
    conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName());
    // generate a test key
    byte[] keyBytes = new byte[AES.KEY_LENGTH];
    new SecureRandom().nextBytes(keyBytes);
    String algorithm = conf.get(HConstants.CRYPTO_KEY_ALGORITHM_CONF_KEY, HConstants.CIPHER_AES);
    Key key = new SecretKeySpec(keyBytes, algorithm);
    // wrap the test key
    byte[] wrappedKeyBytes = EncryptionUtil.wrapKey(conf, "hbase", key);
    assertNotNull(wrappedKeyBytes);
    // unwrap
    Key unwrappedKey = EncryptionUtil.unwrapKey(conf, "hbase", wrappedKeyBytes);
    assertNotNull(unwrappedKey);
    // only secretkeyspec supported for now
    assertTrue(unwrappedKey instanceof SecretKeySpec);
    // did we get back what we wrapped?
    assertTrue("Unwrapped key bytes do not match original", Bytes.equals(keyBytes, unwrappedKey.getEncoded()));
    // unwrap with an incorrect key
    try {
        EncryptionUtil.unwrapKey(conf, "other", wrappedKeyBytes);
        fail("Unwrap with incorrect key did not throw KeyException");
    } catch (KeyException e) {
    // expected
    }
}
Also used : Configuration(org.apache.hadoop.conf.Configuration) SecretKeySpec(javax.crypto.spec.SecretKeySpec) SecureRandom(java.security.SecureRandom) KeyProviderForTesting(org.apache.hadoop.hbase.io.crypto.KeyProviderForTesting) Key(java.security.Key) KeyException(java.security.KeyException) Test(org.junit.Test)

Example 38 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project hbase by apache.

the class TestEncryptionUtil method testWALKeyWrappingWithIncorrectKey.

@Test(expected = KeyException.class)
public void testWALKeyWrappingWithIncorrectKey() throws Exception {
    // set up the key provider for testing to resolve a key for our test subject
    // we don't need HBaseConfiguration for this
    Configuration conf = new Configuration();
    conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName());
    // generate a test key
    byte[] keyBytes = new byte[AES.KEY_LENGTH];
    new SecureRandom().nextBytes(keyBytes);
    String algorithm = conf.get(HConstants.CRYPTO_WAL_ALGORITHM_CONF_KEY, HConstants.CIPHER_AES);
    Key key = new SecretKeySpec(keyBytes, algorithm);
    // wrap the test key
    byte[] wrappedKeyBytes = EncryptionUtil.wrapKey(conf, "hbase", key);
    assertNotNull(wrappedKeyBytes);
    // unwrap with an incorrect key
    EncryptionUtil.unwrapWALKey(conf, "other", wrappedKeyBytes);
}
Also used : Configuration(org.apache.hadoop.conf.Configuration) SecretKeySpec(javax.crypto.spec.SecretKeySpec) SecureRandom(java.security.SecureRandom) KeyProviderForTesting(org.apache.hadoop.hbase.io.crypto.KeyProviderForTesting) Key(java.security.Key) Test(org.junit.Test)

Example 39 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec 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 SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project weixin-java-tools by chanjarster.

the class WxCryptUtil method encrypt.

/**
   * 对明文进行加密.
   *
   * @param plainText 需要加密的明文
   * @return 加密后base64编码的字符串
   */
protected String encrypt(String randomStr, String plainText) {
    ByteGroup byteCollector = new ByteGroup();
    byte[] randomStringBytes = randomStr.getBytes(CHARSET);
    byte[] plainTextBytes = plainText.getBytes(CHARSET);
    byte[] bytesOfSizeInNetworkOrder = number2BytesInNetworkOrder(plainTextBytes.length);
    byte[] appIdBytes = appidOrCorpid.getBytes(CHARSET);
    // randomStr + networkBytesOrder + text + appid
    byteCollector.addBytes(randomStringBytes);
    byteCollector.addBytes(bytesOfSizeInNetworkOrder);
    byteCollector.addBytes(plainTextBytes);
    byteCollector.addBytes(appIdBytes);
    // ... + pad: 使用自定义的填充方式对明文进行补位填充
    byte[] padBytes = PKCS7Encoder.encode(byteCollector.size());
    byteCollector.addBytes(padBytes);
    // 获得最终的字节流, 未加密
    byte[] unencrypted = byteCollector.toBytes();
    try {
        // 设置加密模式为AES的CBC模式
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
        IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
        // 加密
        byte[] encrypted = cipher.doFinal(unencrypted);
        // 使用BASE64对加密后的字符串进行编码
        String base64Encrypted = base64.encodeToString(encrypted);
        return base64Encrypted;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Aggregations

SecretKeySpec (javax.crypto.spec.SecretKeySpec)498 Cipher (javax.crypto.Cipher)194 SecretKey (javax.crypto.SecretKey)142 Mac (javax.crypto.Mac)110 IvParameterSpec (javax.crypto.spec.IvParameterSpec)106 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)94 InvalidKeyException (java.security.InvalidKeyException)67 IOException (java.io.IOException)44 Key (java.security.Key)36 SecureRandom (java.security.SecureRandom)30 Test (org.junit.Test)30 UnsupportedEncodingException (java.io.UnsupportedEncodingException)29 GeneralSecurityException (java.security.GeneralSecurityException)27 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)27 MessageDigest (java.security.MessageDigest)25 BadPaddingException (javax.crypto.BadPaddingException)25 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)25 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)18 PrivateKey (java.security.PrivateKey)18 PublicKey (java.security.PublicKey)16