List of usage examples for org.apache.commons.codec.binary Hex decodeHex
public static byte[] decodeHex(char[] data) throws IllegalArgumentException
From source file:org.apache.hadoop.io.crypto.TokenKeyProvider.java
private Key hex2Key(String strHexKey) throws Exception { // logger.info("Got Hex Key String:" + strHexKey); if (strHexKey == null || strHexKey.isEmpty()) throw new Exception("Secret Key Exchange Fail: Get null or empty Hex Key String"); byte[] rawKey = Hex.decodeHex(strHexKey.toCharArray()); int cryptographicLength = 256; if (rawKey.length == 16) cryptographicLength = 128;/* w w w.j a va2s. com*/ else if (rawKey.length == 32) cryptographicLength = 256; else if (rawKey.length == 0) throw new Exception("Secret Key Exchange Fail: Not Hex Format Key String"); else throw new Exception( "Secret Key Exchange Fail: Invalid key length(only support 16(128)/32(256) bytes): rawKey.length=" + rawKey.length); // Key key = new Key (keyType, algorithm, 0, format, rawKey); return new Key(Key.KeyType.SYMMETRIC_KEY, "AES", cryptographicLength, "RAW", rawKey); }
From source file:org.apache.hadoop.io.crypto.TokenKeyProvider.java
private Key[] getKeysByToken(String[] keyNames) throws Exception { if (this.strMgmtUrl == null || this.strMgmtUrl.isEmpty()) throw new CryptoException("Please init Key Manager url in first"); logger.debug("MgmtUrl: " + this.strMgmtUrl); logger.debug("Key token id: " + keyToken.getId()); // Init/*from w ww . j a va 2 s. co m*/ KeySaslClient keySaslClient = new KeySaslClient(keyToken); SaslParam saslParam = new SaslParam(SaslUtil.SaslCommand.INIT); saslParam.setPwdId(keyToken.getId()); SaslParam saslParamRecv = keySaslClient.connection(this.strMgmtUrl, saslParam); if (saslParamRecv == null) throw new Exception("No such token: recieve null SASL parameter"); // auth saslParam.setSaslId(saslParamRecv.getSaslId()); saslParam.setCommand(SaslUtil.SaslCommand.AUTH); int loopTimes = 0; final int MAX_LOOP = 2; for (; loopTimes < MAX_LOOP; loopTimes++) { byte[] response = keySaslClient.auth(saslParamRecv.getChallenge()); if (keySaslClient.getSaslAuthStatus().equals(SaslUtil.SaslAuthStatus.AUTH_SUCCESS)) break; saslParam.setResponse(response); logger.debug("response:" + Hex.encodeHexString(saslParam.getResponse())); saslParamRecv = keySaslClient.connection(this.strMgmtUrl, saslParam); if (saslParamRecv == null) throw new Exception("SASL Authendication Challenge Fail: recieve null SASL parameter"); } // data Key[] rawKeys = new Key[keyNames.length]; if (keySaslClient.getSaslAuthStatus().equals(SaslUtil.SaslAuthStatus.AUTH_SUCCESS)) { for (int i = 0; i < keyNames.length; i++) { // for (String keyName: keyNames){ byte[] data = keySaslClient.dataProcess(keyNames[i].getBytes()); saslParam.setData(data); saslParam.setCommand(SaslUtil.SaslCommand.DATA); saslParamRecv = keySaslClient.connection(this.strMgmtUrl, saslParam); if (saslParamRecv == null) throw new Exception("Secret Key Exchange Fail: recieve null SASL parameter"); byte[] dataRecv = keySaslClient.dataUnwrap(saslParamRecv); // logger.debug("Got key:" + new String(dataRecv)); byte[] rawKey = Hex.decodeHex(new String(dataRecv).toCharArray()); int cryptographicLength = 256; if (rawKey.length == 16) cryptographicLength = 128; else if (rawKey.length == 32) cryptographicLength = 256; else if (rawKey.length == 0) throw new Exception("Secret Key Exchange Fail: No such key: " + keyNames[i]); else throw new Exception( "Secret Key Exchange Fail: Invalid key length(only support 16(128)/32(256) bytes): rawKey.length=" + rawKey.length); // Key key = new Key (keyType, algorithm, 0, format, rawKey); rawKeys[i] = new Key(Key.KeyType.SYMMETRIC_KEY, "AES", cryptographicLength, "RAW", rawKey); // logger.info("Got key:" + new String(saslParam.getdata())); } } else { logger.error("Fail to auth: Perhaps exceed auth MAX_LOOP"); throw new Exception("SASL Authendication Fail: Exceed Auth MAX_LOOP"); } return rawKeys; }
From source file:org.apache.hadoop.io.crypto.tool.CryptoApiTool.java
private Key initKey(String sHexKey) throws Exception { if (sHexKey == null) throw new Exception("Fail to get key(cypto.secret.key) from Configuration"); byte[] rawKey = Hex.decodeHex(sHexKey.toCharArray()); int cryptographicLength = 256; if (rawKey.length == 16) cryptographicLength = 128;/* w ww. j av a2s . co m*/ else if (rawKey.length == 32) cryptographicLength = 256; else throw new Exception( "Invalid key length(only support 16(128)/32(256) bytes): rawKey.length=" + rawKey.length); // Key key = new Key (keyType, algorithm, 0, format, rawKey); return new Key(Key.KeyType.SYMMETRIC_KEY, "AES", cryptographicLength, "RAW", rawKey); }
From source file:org.apache.isis.core.commons.encoding.HexUtils.java
public static <T> T decoded(final String hexEncoded, Class<T> cls) { final char[] chars = hexEncoded.toCharArray(); byte[] bytes; try {/*from ww w. ja v a2s . co m*/ bytes = Hex.decodeHex(chars); final ByteArrayInputStream bais = new ByteArrayInputStream(bytes); final DataInputStreamExtended inputImpl = new DataInputStreamExtended(bais); return inputImpl.readEncodable(cls); } catch (final IOException ex) { throw new IsisException("Failed to read object", ex); } catch (final DecoderException ex) { throw new IsisException("Failed to hex decode object", ex); } }
From source file:org.apache.metron.stellar.common.utils.hashing.tlsh.TLSHHasher.java
public Map<String, String> bin(String hash) throws DecoderException { Random r = new Random(0); byte[] h = Hex.decodeHex(hash.substring(2 * checksumOption.getChecksumLength()).toCharArray()); BitSet vector = BitSet.valueOf(h); int n = vector.length(); Map<String, String> ret = new HashMap<>(); boolean singleHash = hashes.size() == 1; for (int numHashes : hashes) { BitSet projection = new BitSet(); for (int i = 0; i < numHashes; ++i) { int index = r.nextInt(n); projection.set(i, vector.get(index)); }/*w w w . ja v a 2 s. c om*/ String outputHash = numHashes + Hex.encodeHexString(projection.toByteArray()); if (singleHash) { ret.put(TLSH_BIN_KEY, outputHash); } else { ret.put(TLSH_BIN_KEY + "_" + numHashes, outputHash); } } return ret; }
From source file:org.apache.myfaces.application.viewstate.RandomKeyFactory.java
@Override public byte[] decode(String value) { try {/* w ww . j a va 2 s . c om*/ return Hex.decodeHex(value.toCharArray()); } catch (DecoderException ex) { // Cannot decode, ignore silently, later it will be handled as // ViewExpiredException } return null; }
From source file:org.apache.myfaces.ext202patch.application.viewstate.RandomKeyFactory.java
@Override public byte[] decode(String value) { try {//from w w w . j a va 2 s . co m return Hex.decodeHex(value.toCharArray()); } catch (DecoderException ex) { // Cannot decode, ignore silently, later it will be handled as // ViewExpiredException // Cannot decode, ignore silently, later it will be handled as // ViewExpiredException } return null; }
From source file:org.apache.nifi.processors.standard.EncryptContent.java
private List<ValidationResult> validateKeyed(EncryptionMethod encryptionMethod, KeyDerivationFunction kdf, String keyHex) {//from w w w. ja v a 2 s . co m List<ValidationResult> validationResults = new ArrayList<>(); boolean limitedStrengthCrypto = !PasswordBasedEncryptor.supportsUnlimitedStrength(); if (limitedStrengthCrypto) { if (encryptionMethod.isUnlimitedStrength()) { validationResults.add(new ValidationResult.Builder().subject(ENCRYPTION_ALGORITHM.getName()) .explanation(encryptionMethod.name() + " (" + encryptionMethod.getAlgorithm() + ") is not supported by this JVM due to lacking JCE Unlimited " + "Strength Jurisdiction Policy files. See Admin Guide.") .build()); } } int allowedKeyLength = PasswordBasedEncryptor.getMaxAllowedKeyLength(ENCRYPTION_ALGORITHM.getName()); if (StringUtils.isEmpty(keyHex)) { validationResults.add(new ValidationResult.Builder().subject(RAW_KEY_HEX.getName()) .explanation(RAW_KEY_HEX.getDisplayName() + " is required when using algorithm " + encryptionMethod.getAlgorithm() + ". See Admin Guide.") .build()); } else { byte[] keyBytes = new byte[0]; try { keyBytes = Hex.decodeHex(keyHex.toCharArray()); } catch (DecoderException e) { validationResults.add(new ValidationResult.Builder().subject(RAW_KEY_HEX.getName()) .explanation("Key must be valid hexadecimal string. See Admin Guide.").build()); } if (keyBytes.length * 8 > allowedKeyLength) { validationResults.add(new ValidationResult.Builder().subject(RAW_KEY_HEX.getName()) .explanation("Key length greater than " + allowedKeyLength + " bits is not supported by this JVM" + " due to lacking JCE Unlimited Strength Jurisdiction Policy files. See Admin Guide.") .build()); } if (!CipherUtility.isValidKeyLengthForAlgorithm(keyBytes.length * 8, encryptionMethod.getAlgorithm())) { List<Integer> validKeyLengths = CipherUtility .getValidKeyLengthsForAlgorithm(encryptionMethod.getAlgorithm()); validationResults.add(new ValidationResult.Builder().subject(RAW_KEY_HEX.getName()) .explanation("Key must be valid length [" + StringUtils.join(validKeyLengths, ", ") + "]. See Admin Guide.") .build()); } } // Perform some analysis on the selected encryption algorithm to ensure the JVM can support it and the associated key List<String> kdfsForKeyedCipher = getKDFsForKeyedCipher(); if (kdf == null || !kdfsForKeyedCipher.contains(kdf.name())) { validationResults.add(new ValidationResult.Builder().subject(KEY_DERIVATION_FUNCTION.getName()) .explanation(KEY_DERIVATION_FUNCTION.getDisplayName() + " is required to be " + StringUtils.join(kdfsForKeyedCipher, ", ") + " when using algorithm " + encryptionMethod.getAlgorithm()) .build()); } return validationResults; }
From source file:org.apache.nifi.processors.standard.EncryptContent.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { FlowFile flowFile = session.get();/* w w w .j ava 2 s. co m*/ if (flowFile == null) { return; } final ComponentLog logger = getLogger(); final String method = context.getProperty(ENCRYPTION_ALGORITHM).getValue(); final EncryptionMethod encryptionMethod = EncryptionMethod.valueOf(method); final String providerName = encryptionMethod.getProvider(); final String algorithm = encryptionMethod.getAlgorithm(); final String password = context.getProperty(PASSWORD).getValue(); final KeyDerivationFunction kdf = KeyDerivationFunction .valueOf(context.getProperty(KEY_DERIVATION_FUNCTION).getValue()); final boolean encrypt = context.getProperty(MODE).getValue().equalsIgnoreCase(ENCRYPT_MODE); Encryptor encryptor; StreamCallback callback; try { if (isPGPAlgorithm(algorithm)) { final String filename = flowFile.getAttribute(CoreAttributes.FILENAME.key()); final String publicKeyring = context.getProperty(PUBLIC_KEYRING).getValue(); final String privateKeyring = context.getProperty(PRIVATE_KEYRING).getValue(); if (encrypt && publicKeyring != null) { final String publicUserId = context.getProperty(PUBLIC_KEY_USERID).getValue(); encryptor = new OpenPGPKeyBasedEncryptor(algorithm, providerName, publicKeyring, publicUserId, null, filename); } else if (!encrypt && privateKeyring != null) { final char[] keyringPassphrase = context.getProperty(PRIVATE_KEYRING_PASSPHRASE).getValue() .toCharArray(); encryptor = new OpenPGPKeyBasedEncryptor(algorithm, providerName, privateKeyring, null, keyringPassphrase, filename); } else { final char[] passphrase = Normalizer.normalize(password, Normalizer.Form.NFC).toCharArray(); encryptor = new OpenPGPPasswordBasedEncryptor(algorithm, providerName, passphrase, filename); } } else if (kdf.equals(KeyDerivationFunction.NONE)) { // Raw key final String keyHex = context.getProperty(RAW_KEY_HEX).getValue(); encryptor = new KeyedEncryptor(encryptionMethod, Hex.decodeHex(keyHex.toCharArray())); } else { // PBE final char[] passphrase = Normalizer.normalize(password, Normalizer.Form.NFC).toCharArray(); encryptor = new PasswordBasedEncryptor(encryptionMethod, passphrase, kdf); } if (encrypt) { callback = encryptor.getEncryptionCallback(); } else { callback = encryptor.getDecryptionCallback(); } } catch (final Exception e) { logger.error("Failed to initialize {}cryption algorithm because - ", new Object[] { encrypt ? "en" : "de", e }); session.rollback(); context.yield(); return; } try { final StopWatch stopWatch = new StopWatch(true); flowFile = session.write(flowFile, callback); logger.info("successfully {}crypted {}", new Object[] { encrypt ? "en" : "de", flowFile }); session.getProvenanceReporter().modifyContent(flowFile, stopWatch.getElapsed(TimeUnit.MILLISECONDS)); session.transfer(flowFile, REL_SUCCESS); } catch (final ProcessException e) { logger.error("Cannot {}crypt {} - ", new Object[] { encrypt ? "en" : "de", flowFile, e }); session.transfer(flowFile, REL_FAILURE); } }
From source file:org.apache.nifi.processors.standard.SplitContent.java
@OnScheduled public void initializeByteSequence(final ProcessContext context) throws DecoderException { final String bytePattern = context.getProperty(BYTE_SEQUENCE).getValue(); final String format = context.getProperty(FORMAT).getValue(); if (HEX_FORMAT.getValue().equals(format)) { this.byteSequence.set(Hex.decodeHex(bytePattern.toCharArray())); } else {/*from w w w .j a va 2s .co m*/ this.byteSequence.set(bytePattern.getBytes(StandardCharsets.UTF_8)); } }