/*
parseEncryptionData
Takes the json string in the encryptiondata metadata field of the encrypted
blob and parses out the key and iv. Returns the pair as key = key, iv = value.
428409
private SimpleEntry<String, String> parseEncryptionData(String jsonEncryptionData)
  throws SnowflakeSQLException
  {
    ObjectMapper mapper = ObjectMapperFactory.getObjectMapper();
    JsonFactory factory = mapper.getJsonFactory();
    try
    {
      JsonParser parser = factory.createJsonParser(jsonEncryptionData);
      JsonNode encryptionDataNode = mapper.readTree(parser);

      String iv = encryptionDataNode.get("ContentEncryptionIV").asText();
      String key = encryptionDataNode.get("WrappedContentKey").get("EncryptedKey").asText();

      return new SimpleEntry<String, String>(key, iv);
    }
    catch (Exception ex)
    {
      throw new SnowflakeSQLException(ex, SqlState.SYSTEM_ERROR,
                                      ErrorCode.IO_ERROR.getMessageCode(),
                                      "Error parsing encryption data as json" + ": " +
                                      ex.getMessage());
    }
  }
927843
byte[] getRawData() {

    // Header: [Version | Options]
    byte[] header = new byte[] { (byte) getVersionNumber(), 0 };

    if (isPasswordBased) {
      header[1] |= FLAG_PASSWORD;
    }

    // Pack result
    final int dataSize;

    if (isPasswordBased) {
      dataSize = header.length + encryptionSalt.length + hmacSalt.length
          + iv.length + ciphertext.length + hmac.length;
    } else {
      dataSize = header.length + iv.length + ciphertext.length + hmac.length;
    }

    byte[] result = new byte[dataSize];

    System.arraycopy(header, 0, result, 0, header.length);

    if (isPasswordBased) {
      System.arraycopy(encryptionSalt, 0, result, header.length,
          encryptionSalt.length);
      System.arraycopy(hmacSalt, 0, result, header.length
          + encryptionSalt.length, hmacSalt.length);
      System.arraycopy(iv, 0, result, header.length + encryptionSalt.length
          + hmacSalt.length, iv.length);
      System.arraycopy(ciphertext, 0, result, header.length
          + encryptionSalt.length + hmacSalt.length + iv.length,
          ciphertext.length);
      System.arraycopy(hmac, 0, result, header.length + encryptionSalt.length
          + hmacSalt.length + iv.length + ciphertext.length, hmac.length);
    } else {
      System.arraycopy(iv, 0, result, header.length, iv.length);
      System.arraycopy(ciphertext, 0, result, header.length + iv.length,
          ciphertext.length);
      System.arraycopy(hmac, 0, result, header.length + iv.length
          + ciphertext.length, hmac.length);
    }

    return result;
  }
23027
private Object decrypt(JsonObject object, String providerName) throws Exception {
        Object decrypted;

        String key = object.getString("kid");
        String alg = object.getString("alg");

        CryptoProvider provider = this.cryptoManager.getProvider(providerName);

        if (!provider.checkAlgorithmNameMatch(alg)) {
            cryptoManager.throwMissingPublicKeyEx(providerName);
        }

        if (!key.contentEquals(provider.getKeyStoreProvider().publicKeyName())) {
            cryptoManager.throwMissingPublicKeyEx(providerName);
        }

        byte[] encryptedBytes;
        String encryptedValueWithConfig;

        if (object.containsKey("iv")) {
            encryptedValueWithConfig = object.getString("kid") + object.getString("alg")
                    + object.getString("iv") + object.getString("ciphertext");

            byte[] encrypted = Base64.decode(object.getString("ciphertext"));
            byte[] iv = Base64.decode(object.getString("iv"));
            encryptedBytes = new byte[iv.length + encrypted.length];
            System.arraycopy(iv, 0, encryptedBytes, 0, iv.length);
            System.arraycopy(encrypted, 0, encryptedBytes, iv.length, encrypted.length);
        } else {
            encryptedValueWithConfig = object.getString("kid") + object.getString("alg")
                    + object.getString("ciphertext");
            encryptedBytes = Base64.decode(object.getString("ciphertext"));
        }

        if (object.containsKey("sig")) {
            byte[] signature = Base64.decode(object.getString("sig"));

            if (!provider.verifySignature(encryptedValueWithConfig.getBytes(), signature)) {
                cryptoManager.throwSigningFailedEx(providerName);
            }
        }

        byte[] decryptedBytes = provider.decrypt(encryptedBytes);
        String decryptedString = new String(decryptedBytes, Charset.forName("UTF-8"));
        decrypted = JacksonTransformers.MAPPER.readValue(decryptedString, Object.class);
        if (decrypted instanceof Map) {
            decrypted = JsonObject.from((Map<String, ?>) decrypted);
        } else if (decrypted instanceof List) {
            decrypted = JsonArray.from((List<?>) decrypted);
        }
        return decrypted;
    }
1095280
private boolean validateEncryptionKeyData(KeyData data) {
        if (data.getIv().length != ENCRYPTIONKEYCHAINMANAGER_AES_IV_SIZE) {
            LOGGER.warning("IV does not have the expected size: " +
                    ENCRYPTIONKEYCHAINMANAGER_AES_IV_SIZE + " bytes");
            return false;
        }
        return true;
    }
881426
function parse_DataSpaceVersionInfo(blob) {
	var o = {};
	o.id = blob.read_shift(0, 'lpp4');
	o.R = parse_CRYPTOVersion(blob, 4);
	o.U = parse_CRYPTOVersion(blob, 4);
	o.W = parse_CRYPTOVersion(blob, 4);
	return o;
}
554318
function(data) {
      if (!(data && 'function' === typeof data.isBase64 && data.isBase64())) {
        throw new CError('wrong data format to decrypt').log();
      }
      return JSON.parse(this.encoder.decryptAes(data, this.getSecret()));
    }
1162023
function parse_encrypted(&$p)
    {
        $struct = $p['structure'];

        // S/MIME
        if ($p['mimetype'] == 'application/pkcs7-mime') {
            $this->parse_smime_encrypted($p);
        }
        // PGP/MIME: RFC3156
        // The multipart/encrypted MUST consist of exactly two parts. The first
        // MIME body part must have a content type of "application/pgp-encrypted".
        // This body contains the control information.
        // The second MIME body part MUST contain the actual encrypted data.  It
        // must be labeled with a content type of "application/octet-stream".
        else if (count($struct->parts) == 2
            && $struct->parts[0] && $struct->parts[0]->mimetype == 'application/pgp-encrypted'
            && $struct->parts[1] && $struct->parts[1]->mimetype == 'application/octet-stream'
        ) {
            $this->parse_pgp_encrypted($p);
        }
    }
1073517
function parse_EncInfoStd(blob) {
	var flags = blob.read_shift(4);
	if((flags & 0x3F) != 0x24) throw new Error("EncryptionInfo mismatch");
	var sz = blob.read_shift(4);
	//var tgt = blob.l + sz;
	var hdr = parse_EncryptionHeader(blob, sz);
	var verifier = parse_EncryptionVerifier(blob, blob.length - blob.l);
	return { t:"Std", h:hdr, v:verifier };
}
1194392
public byte[] decryptData(byte[] data) throws SymmetricKeyException {
        if (data.length < IV_SIZE)
            throw new SymmetricKeyException("Invalid encrypted data, no IV prepended");
        byte[] iv = ArrayUtils.subarray(data, 0, IV_SIZE);
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE, iv);
        try {
            return cipher.doFinal(data, iv.length, data.length - iv.length);
        } catch (Exception e) {
            throw new SymmetricKeyException(e);
        }
    }
651642
function parseKey (inp) {
    var res = parseString(inp);
    if (res) return res;
  
    var match = inp.takeAPeek(JS_IDENT);
    if (match) return match[0]
  }
1242988
public static ArrayList<TagValue> DecodePKCS8(byte[] encodedData) throws CoseException 
    {
        TagValue pkcs8 = DecodeCompound(0, encodedData);
        if (pkcs8.tag != 0x30) throw new CoseException("Invalid PKCS8 structure");
        ArrayList<TagValue> retValue = pkcs8.list;
        if (retValue.size() != 3 && retValue.size() != 4) {
            throw new CoseException("Invalid PKCS8 structure");
        }

        // Version number - we currently only support one version
        if (retValue.get(0).tag != 2 && ((byte[]) retValue.get(0).value)[0] != 0) {
            throw new CoseException("Invalid PKCS8 structure");
        }

        // Algorithm identifier
        if (retValue.get(1).tag != 0x30) throw new CoseException("Invalid PKCS8 structure");
        if (retValue.get(1).list.isEmpty() || retValue.get(1).list.size() > 2) {
            throw new CoseException("Invalid PKCS8 structure");
        }
        if (retValue.get(1).list.get(0).tag != 6) throw new CoseException("Invalid PKCS8 structure");
        //  Dont check the next item as it is an ANY
        
        if (retValue.get(2).tag != 4) throw new CoseException("Invalid PKCS8 structure");
        
        // This is attributes, but we are not going to check for correctness.
        if (retValue.size() == 4 && retValue.get(3).tag != 0xa0) {
            throw new CoseException("Invalid PKCS8 structure");
        }
        
        //  Decode the contents of the octet string PrivateKey
        
        byte[] pk = (byte[]) retValue.get(2).value;
        TagValue pkd = DecodeCompound(0, pk);
        ArrayList<TagValue> pkdl = pkd.list;
        if (pkd.tag != 0x30) throw new CoseException("Invalid ECPrivateKey");
        if (pkdl.size() < 2 || pkdl.size() > 4) throw new CoseException("Invalid ECPrivateKey");
        
        if (pkdl.get(0).tag != 2 && ((byte[]) retValue.get(0).value)[0] != 1) {
            throw new CoseException("Invalid ECPrivateKey");
        }
        
        if (pkdl.get(1).tag != 4) throw new CoseException("Invalid ECPrivateKey");
        
        if (pkdl.size() > 2) {
            if ((pkdl.get(2).tag & 0xff) != 0xA0) {
                if (pkdl.size() != 3 || (pkdl.get(2).tag & 0xff) != 0xa1) {
                    throw new CoseException("Invalid ECPrivateKey");
                }
            } else {
                if (pkdl.size() == 4 && (pkdl.get(3).tag & 0xff) != 0xa1) throw new CoseException("Invalid ECPrivateKey");                
            }
        }
        
        retValue.get(2).list = pkdl;
        retValue.get(2).value = null;
        retValue.get(2).tag = 0x30;
        
        return retValue;
    }
1213459
@CheckForNull
    public static Secret decrypt(@CheckForNull String data) {
        if(!isValidData(data))      return null;

        if (data.startsWith("{") && data.endsWith("}")) { //likely CBC encrypted/containing metadata but could be plain text
            byte[] payload;
            try {
                payload = Base64.getDecoder().decode(data.substring(1, data.length()-1));
            } catch (IllegalArgumentException e) {
                return null;
            }
            switch (payload[0]) {
                case PAYLOAD_V1:
                    // For PAYLOAD_V1 we use this byte shifting model, V2 probably will need DataOutput
                    int ivLength = ((payload[1] & 0xff) << 24)
                            | ((payload[2] & 0xff) << 16)
                            | ((payload[3] & 0xff) << 8)
                            | (payload[4] & 0xff);
                    int dataLength = ((payload[5] & 0xff) << 24)
                            | ((payload[6] & 0xff) << 16)
                            | ((payload[7] & 0xff) << 8)
                            | (payload[8] & 0xff);
                    if (payload.length != 1 + 8 + ivLength + dataLength) {
                        // not valid v1
                        return null;
                    }
                    byte[] iv = Arrays.copyOfRange(payload, 9, 9 + ivLength);
                    byte[] code = Arrays.copyOfRange(payload, 9+ivLength, payload.length);
                    String text;
                    try {
                        text = new String(KEY.decrypt(iv).doFinal(code), UTF_8);
                    } catch (GeneralSecurityException e) {
                        // it's v1 which cannot be historical, but not decrypting
                        return null;
                    }
                    return new Secret(text, iv);
                default:
                    return null;
            }
        } else {
            try {
                return HistoricalSecrets.decrypt(data, KEY);
            } catch (UnsupportedEncodingException e) {
                throw new Error(e); // impossible
            } catch (GeneralSecurityException | IOException e) {
                return null;
            }
        }
    }
1288334
function parseKeyValue(/**string*/keyValue) {
  var obj = {};
  forEach((keyValue || "").split('&'), function(keyValue) {
    var splitPoint, key, val;
    if (keyValue) {
      key = keyValue = keyValue.replace(/\+/g,'%20');
      splitPoint = keyValue.indexOf('=');
      if (splitPoint !== -1) {
        key = keyValue.substring(0, splitPoint);
        val = keyValue.substring(splitPoint + 1);
      }
      key = tryDecodeURIComponent(key);
      if (isDefined(key)) {
        val = isDefined(val) ? tryDecodeURIComponent(val) : true;
        if (!hasOwnProperty.call(obj, key)) {
          obj[key] = val;
        } else if (isArray(obj[key])) {
          obj[key].push(val);
        } else {
          obj[key] = [obj[key],val];
        }
      }
    }
  });
  return obj;
}
432693
String parseObjectKey() throws IOException {
        if (cachedObjectKey != null) {
            String key = cachedObjectKey;
            cachedObjectKey = null;
            return key;
        }
        String str = parseString();
        acceptEvent(JsonEvent.COLON);
        return str;
    }
636023
function parseInputData(data) {
			var keyValRegExPattern = /[a-zA-Z]*:/g;
			var keys = data.match(keyValRegExPattern),
				values = data.split(keyValRegExPattern),
				parsedObject = {};

			// Pop the first blank one off the top
			values.shift();


			for(var i=values.length-1; i >=0; i--) {
				var value = values[i],
					key = keys[i];

				// Trim whitespace
				value = value.trim();

				// Trim any trailing commas
				if(value[value.length-1] === ",") {
					value = value.substring(0, value.length-1);
				}

				// Add to object and trim trailing : from key
				parsedObject[ key.substring(0,key.length-1) ] = value;
			}

			return parsedObject;

		}
911148
public static byte[] decrypt(byte[] data, byte[] key) {
        checkNotNull(data);
        checkNotNull(key);
        checkArgument(key.length >= 5 && key.length <= 256);
        StreamCipher rc4 = new RC4Engine();
        rc4.init(false, new KeyParameter(key));
        byte[] decrypted = new byte[data.length];
        rc4.processBytes(data, 0, data.length, decrypted, 0);
        return decrypted;
    }
864067
private String toJsonString() {
        Map<String, String> map = new HashMap<String, String>();
        byte[] encryptedCEK = getEncryptedCEK();
        map.put(Headers.CRYPTO_KEY_V2, Base64.encodeAsString(encryptedCEK));
        byte[] iv = cipherLite.getIV();
        map.put(Headers.CRYPTO_IV, Base64.encodeAsString(iv));
        map.put(Headers.MATERIALS_DESCRIPTION, kekMaterialDescAsJson());
        // The CRYPTO_CEK_ALGORITHM, CRYPTO_TAG_LENGTH and
        // CRYPTO_KEYWRAP_ALGORITHM were not available in the Encryption Only
        // (EO) implementation
        ContentCryptoScheme scheme = getContentCryptoScheme();
        map.put(Headers.CRYPTO_CEK_ALGORITHM, scheme.getCipherAlgorithm());
        int tagLen = scheme.getTagLengthInBits();
        if (tagLen > 0)
            map.put(Headers.CRYPTO_TAG_LENGTH, String.valueOf(tagLen));
        String keyWrapAlgo = getKeyWrappingAlgorithm();
        if (keyWrapAlgo != null)
            map.put(Headers.CRYPTO_KEYWRAP_ALGORITHM, keyWrapAlgo);
        return Jackson.toJsonString(map);
    }