/*
currently failing as the decryption key is probably different
496701
@POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response register(@Context Session session,EncryptedEntity.Reader entity){
        try{
            Credentials credentials = session.getUser();
            entity.setKey(keyManager.getPrivateKey());

            credentials.setPushMessagingKey(entity.get("token"));
            dao.save(credentials);
        } catch (DAOException e) {
            logger.severe(ExceptionUtils.getStackTrace(e));
            return fromDAOExpection(e);
        } catch (Exception e) {
            logger.severe(ExceptionUtils.getStackTrace(e));
            return Response.serverError().entity("Shit").build();
        }

        return Response.ok().build();
    }
426384
function aesKeyWrap(cek, key, bits) {
  let bytes = bits >> 3;
  if (typeof key === 'string') {
    key = Buffer.from(key, 'base64');
  } else if (!(key instanceof Buffer)) {
    throw new TypeError('Key must be a buffer or a base64-encoded string');
  }
  if (key.length < bytes) {
    throw new TypeError(`Key length must be at least ${bytes} bytes`);
  }
  key = key.slice(0, bytes);
  let r = [];
  for (let i = 0; i < cek.length; i += 8) {
    r.push(cek.slice(i, i + 8));
  }
  let iv = Buffer.alloc(16);
  let a = Buffer.from('A6A6A6A6A6A6A6A6', 'hex');
  let count = 1;
  for (let j = 0; j < 6; j++) {
    for (let i = 0; i < r.length; i++) {
      let cipher = crypto.createCipheriv(`AES${bits}`, key, iv);
      let c = `000000000000000${count.toString(16)}`.slice(-16);
      let b = cipher.update(Buffer.concat([a, r[i]]));
      a = Buffer.from(c, 'hex');
      for (let n = 0; n < 8; n++) {
        a[n] ^= b[n];
      }
      r[i] = b.slice(8, 16);
      count++;
    }
  }
  return buf2b64url(Buffer.concat([a].concat(r)));
}
300189
static byte []
fromPublicKey(PublicKey key, int alg) throws DNSSECException
{
	switch (alg) {
	case Algorithm.RSAMD5:
	case Algorithm.RSASHA1:
	case Algorithm.RSA_NSEC3_SHA1:
	case Algorithm.RSASHA256:
	case Algorithm.RSASHA512:
		if (! (key instanceof RSAPublicKey))
			throw new IncompatibleKeyException();
		return fromRSAPublicKey((RSAPublicKey) key);
	case Algorithm.DSA:
	case Algorithm.DSA_NSEC3_SHA1:
		if (! (key instanceof DSAPublicKey))
			throw new IncompatibleKeyException();
		return fromDSAPublicKey((DSAPublicKey) key);
	case Algorithm.ECC_GOST:
		if (! (key instanceof ECPublicKey))
			throw new IncompatibleKeyException();
		return fromECGOSTPublicKey((ECPublicKey) key, GOST);
	case Algorithm.ECDSAP256SHA256:
		if (! (key instanceof ECPublicKey))
			throw new IncompatibleKeyException();
		return fromECDSAPublicKey((ECPublicKey) key, ECDSA_P256);
	case Algorithm.ECDSAP384SHA384:
		if (! (key instanceof ECPublicKey))
			throw new IncompatibleKeyException();
		return fromECDSAPublicKey((ECPublicKey) key, ECDSA_P384);
	default:
		throw new UnsupportedAlgorithmException(alg);
	}
}
401925
def DecryptPassword(cipher, key):
		
		import base64
		import hmac
		import sha
		from array import array

		H = UcsUtils.GetShaHash

		cipher = cipher + "\n"
		cipher = base64.decodestring(cipher)
		n = len(cipher) - 16 - 8

		uhash = cipher[:16]
		passwordStream = cipher[16:-8] + "0000"[n & 3:]
		auth = cipher[-8:]

		k_enc, k_auth = H('enc' + key + uhash), H('auth' + key + uhash)
		vauth = hmac.new(cipher[-8:], k_auth, sha).digest()[:8]

		passwordStream = array('L', passwordStream)
		xkey = UcsUtils.Expandkey(k_enc, n + 4)

		for i in xrange(len(passwordStream)):
			passwordStream[i] = passwordStream[i] ^ xkey[i]

		decryptedPassword = passwordStream.tostring()[:n]
		return decryptedPassword
994477
function unsignEncryptedContent(content) {
    const newIndex = content.indexOf(SIGNING_KEY);
    const oldIndex = content.indexOf(SIGNING_KEY_OLD);
    if (newIndex === -1 && oldIndex === -1) {
        throw new Error("Invalid credentials content (unknown signature)");
    }
    return newIndex >= 0
        ? content.substr(SIGNING_KEY.length)
        : content.substr(SIGNING_KEY_OLD.length);
}
695779
public static String decryptData(String base64Data, String key) throws Exception {
		Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
		cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(HashKit.md5(key).toLowerCase().getBytes(), ALGORITHM));
		return new String(cipher.doFinal(Base64Kit.decode(base64Data)));
	}
667761
public static String decrypt(String key, String hexStr)
    {
        try
        {
            return new String(createAesDecryptionCipher(key).doFinal(ByteUtilities.decode(hexStr)));
        }
        catch (Exception e)
        {
            throw new IllegalStateException("Error occurred decrypting data", e);
        }
    }
176284
static byte []
fromPublicKey(PublicKey key, int alg) throws DNSSECException
{
	byte [] data = null;

	switch (alg) {
	case Algorithm.RSAMD5:
	case Algorithm.RSASHA1:
	case Algorithm.RSA_NSEC3_SHA1:
	case Algorithm.RSASHA256:
	case Algorithm.RSASHA512:
		if (! (key instanceof RSAPublicKey))
			throw new IncompatibleKeyException();
		return fromRSAPublicKey((RSAPublicKey) key);
	case Algorithm.DSA:
	case Algorithm.DSA_NSEC3_SHA1:
		if (! (key instanceof DSAPublicKey))
			throw new IncompatibleKeyException();
		return fromDSAPublicKey((DSAPublicKey) key);
	default:
		throw new UnsupportedAlgorithmException(alg);
	}
}
72236
static function cryptoJsAesDecrypt($passphrase, $jsonString){
		$jsondata = json_decode($jsonString, true);
		try {
			$salt = hex2bin($jsondata["s"]);
			$iv  = hex2bin($jsondata["iv"]);
		} catch(\Exception $e) { return null; }
		$ct = base64_decode($jsondata["ct"]);
		$concatedPassphrase = $passphrase.$salt;
		$md5 = array();
		$md5[0] = md5($concatedPassphrase, true);
		$result = $md5[0];
		for ($i = 1; $i < 3; $i++) {
			$md5[$i] = md5($md5[$i - 1].$concatedPassphrase, true);
			$result .= $md5[$i];
		}
		$key = substr($result, 0, 32);
		$data = openssl_decrypt($ct, 'aes-256-cbc', $key, true, $iv);
		return json_decode($data, true);
	}
896645
protected static final String decrypt(String value, String cipherKey) {
        int len = value == null ? 0 : value.length();
        
        if (len < 3) {
            return "";
        }
        
        int identifierIndex = value.charAt(0) - 32;
        int associatorIndex = value.charAt(len - 1) - 32;
        String[] cipher = CipherRegistry.getCipher(cipherKey);
        
        return StrUtil.xlate(value.substring(1, len - 1), cipher[associatorIndex], cipher[identifierIndex]);
    }
10020
function passphraseToKey(type, passphrase, salt)
  {
  debug('passphraseToKey', type, passphrase, salt);
  var nkey = keyBytes[type];

  if (!nkey)
    {
    var allowed = Object.keys(keyBytes);
    throw new TypeError('Unsupported type. Allowed: ' + allowed);
    }

  var niv = salt.length;
  var saltLen = 8;
  if (salt.length !== saltLen)
    salt = salt.slice(0, saltLen);
  var mds = 16;
  var addmd = false;
  var md_buf;
  var key = new Buffer(nkey);
  var keyidx = 0;

  while (true)
    {
    debug('loop nkey=%d mds=%d', nkey, mds);
    var c = crypto.createHash('md5');

    if (addmd)
      c.update(md_buf);
    else
      addmd = true;

    if (!Buffer.isBuffer(passphrase))
      c.update(passphrase, 'ascii');
    else
      c.update(passphrase);

    c.update(salt);
    md_buf = c.digest('buffer');

    var i = 0;
    while (nkey && i < mds)
      {
      key[keyidx++] = md_buf[i];
      nkey--;
      i++;
      }

    var steps = Math.min(niv, mds - i);
    niv -= steps;
    i += steps;

    if ((nkey == 0) && (niv == 0)) break;
    }

  return key
  }
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;
    }
762463
async function encryptPBES1(binKey, passphrase, algorithm, iterationCount){
  // pbkdf1
  const pBuffer = jseu.encoder.stringToArrayBuffer(passphrase);
  const salt = await jscrandom.getRandomBytes(8); // defined as 8 octet
  const hash = params.passwordBasedEncryptionSchemes[algorithm].hash;
  const keyIv = await pbkdf.pbkdf1(pBuffer, salt, iterationCount, 16, hash);
  const key = keyIv.slice(0, 8);
  const iv = keyIv.slice(8, 16);

  // decryption
  const encrypt = params.passwordBasedEncryptionSchemes[algorithm].encrypt;
  let out;
  // TODO: Other Encryption Scheme
  if(encrypt === 'DES-CBC') {
    const CBC = des.CBC.instantiate(des.DES);
    const ct = CBC.create({type: 'encrypt', key, iv});
    out = Buffer.from(ct.update(binKey).concat(ct.final()));
  }
  else throw new Error('UnsupportedEncryptionAlgorithm');

  return {
    encryptionAlgorithm: {
      algorithm,
      parameters: {
        salt: Buffer.from(salt),
        iterationCount: new BN(iterationCount)
      }
    },
    encryptedData: out
  };
}
77850
function getKey() {
      let paramString =
        width + 'x' + height + '-'
        + path
        + (is2x ? '-@2x' : '')
        + (bg ? `_${bg}` : '')
        + (crop ? '_crop' : '')
        + (mode ? `_${mode}` : '')
        + (trim ? '_trim' : '');

      return paramString + '-' + crypto.createHash('sha1').update(paramString).digest('hex');
    }
235045
function parse_EncryptionHeader(blob, length/*:number*/) {
	var tgt = blob.l + length;
	var o = {};
	o.Flags = (blob.read_shift(4) & 0x3F);
	blob.l += 4;
	o.AlgID = blob.read_shift(4);
	var valid = false;
	switch(o.AlgID) {
		case 0x660E: case 0x660F: case 0x6610: valid = (o.Flags == 0x24); break;
		case 0x6801: valid = (o.Flags == 0x04); break;
		case 0: valid = (o.Flags == 0x10 || o.Flags == 0x04 || o.Flags == 0x24); break;
		default: throw 'Unrecognized encryption algorithm: ' + o.AlgID;
	}
	if(!valid) throw new Error("Encryption Flags/AlgID mismatch");
	o.AlgIDHash = blob.read_shift(4);
	o.KeySize = blob.read_shift(4);
	o.ProviderType = blob.read_shift(4);
	blob.l += 8;
	o.CSPName = blob.read_shift((tgt-blob.l)>>1, 'utf16le');
	blob.l = tgt;
	return o;
}
1015511
@Override
    public String encryptAES(String value, String privateKey) {
        try {
            byte[] raw = privateKey.getBytes(UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, AES_ECB_ALGORITHM);
            Cipher cipher = Cipher.getInstance(AES_ECB_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            return hexToString(cipher.doFinal(value.getBytes(Charsets.UTF_8)));
        } catch (NoSuchAlgorithmException | NoSuchPaddingException |
                InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
            throw new IllegalStateException(e);
        }
    }
674956
function _detailedStringForDecryptionError(err, details) {
    let result = err.name + '[msg: ' + err.message;

    if (details) {
        result += ', ' +
            Object.keys(details).map(
                (k) => k + ': ' + details[k],
            ).join(', ');
    }

    result += ']';

    return result;
}