public static byte[] wrapKey(Configuration conf, String subject, Key key) throws IOException {
    // Wrap the key with the configured encryption algorithm.
    String algorithm = conf.get(HConstants.CRYPTO_KEY_ALGORITHM_CONF_KEY, HConstants.CIPHER_AES);
    Cipher cipher = Encryption.getCipher(conf, algorithm);
    if (cipher == null) {
      throw new RuntimeException("Cipher '" + algorithm + "' not available");
    }
    EncryptionProtos.WrappedKey.Builder builder = EncryptionProtos.WrappedKey.newBuilder();
    builder.setAlgorithm(key.getAlgorithm());
    byte[] iv = null;
    if (cipher.getIvLength() > 0) {
      iv = new byte[cipher.getIvLength()];
      Bytes.secureRandom(iv);
      builder.setIv(UnsafeByteOperations.unsafeWrap(iv));
    }
    byte[] keyBytes = key.getEncoded();
    builder.setLength(keyBytes.length);
    builder.setHashAlgorithm(Encryption.getConfiguredHashAlgorithm(conf));
    builder
      .setHash(UnsafeByteOperations.unsafeWrap(Encryption.computeCryptoKeyHash(conf, keyBytes)));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Encryption.encryptWithSubjectKey(out, new ByteArrayInputStream(keyBytes), subject, conf, cipher,
      iv);
    builder.setData(UnsafeByteOperations.unsafeWrap(out.toByteArray()));
    // Build and return the protobuf message
    out.reset();
    builder.build().writeDelimitedTo(out);
    return out.toByteArray();
  }
Protect a key by encrypting it with the secret key of the given subject. The configuration must
be set up correctly for key alias resolution.
@param conf    configuration
@param subject subject key alias
@param key     the key
@return the encrypted key bytes
hbase-client/src/main/java/org/apache/hadoop/hbase/security/EncryptionUtil.java