Convert cache key to base64 encoded
cert id

@param ocsp_cache_key Cache key to encode
189995
private static String encodeCacheKey(OcspResponseCacheKey ocsp_cache_key)
  {
    try
    {
      DigestCalculator digest = new SHA1DigestCalculator();
      AlgorithmIdentifier algo = digest.getAlgorithmIdentifier();
      ASN1OctetString nameHash = ASN1OctetString.getInstance(ocsp_cache_key.nameHash);
      ASN1OctetString keyHash = ASN1OctetString.getInstance(ocsp_cache_key.keyHash);
      ASN1Integer snumber = new ASN1Integer(ocsp_cache_key.serialNumber);
      CertID cid = new CertID(algo, nameHash, keyHash, snumber);
      return Base64.encodeBase64String(cid.toASN1Primitive().getEncoded());
    }
    catch (Exception ex)
    {
      LOGGER.debug("Failed to encode cache key to base64 encoded cert id");
    }
    return null;
  }
624674
def _make_cache_key(key_prefix):
    
    if callable(key_prefix):
        cache_key = key_prefix()
    elif '%s' in key_prefix:
        cache_key = key_prefix % request.path
    else:
        cache_key = key_prefix

    cache_key = cache_key.encode('utf-8')

    return cache_key
169815
private String getCacheKey(String[] keys, CmsDbContext dbc) {

        if (!dbc.getProjectId().isNullUUID()) {
            return "";
        }
        StringBuffer b = new StringBuffer(64);
        int len = keys.length;
        if (len > 0) {
            for (int i = 0; i < len; i++) {
                b.append(keys[i]);
                b.append('_');
            }
        }
        if (dbc.currentProject().isOnlineProject()) {
            b.append("+");
        } else {
            b.append("-");
        }
        return b.toString();
    }
323295
public function setCacheSecurityKey($cacheSecurityKey)
    {
        $this->cacheSecurityKey = $cacheSecurityKey;
        $this->debug->debug(__FUNCTION__, 'setCacheSecurityKey: ', $this->cacheSecurityKey);
    }
1241740
def get_table_cache_key(db_alias, table):
    
    cache_key = '%s:%s' % (db_alias, table)
    return sha1(cache_key.encode('utf-8')).hexdigest()
1266010
public static String getThumbprint(final X509Certificate cert) throws CertificateEncodingException {

		if(cert == null)
		{
			return null;
		}

		byte[] rawOctets = cert.getEncoded();

		SHA1Digest digest = new SHA1Digest();

		byte[] digestOctets = new byte[digest.getDigestSize()];

		digest.update(rawOctets, 0, rawOctets.length);

		digest.doFinal(digestOctets, 0);

		return new String(Base64.encode(digestOctets));
	}
893123
public int writeCacheEntry(CacheEntry ce) {

        final String methodName = "writeCacheEntry()";
        int returnCode = NO_EXCEPTION;
        Exception diskException = null;
        this.invalidationBuffer.remove(ce.id);
        byte[] serializedData = null; // retrieve byte array directly (avoid copy)
        int serializedDataLength = -1;
        try {
            ce.skipValueSerialized = true;
            serializedData = SerializationUtility.serialize(ce);
            serializedDataLength = serializedData.length;
        } catch (Exception ex) {
            returnCode = SERIALIZATION_EXCEPTION;
            com.ibm.ws.ffdc.FFDCFilter.processException(ex, "com.ibm.ws.cache.HTODDynacache.writeCacheEntry", "1174", this);
            if (tc.isDebugEnabled())
                Tr.debug(tc, methodName, "cacheName=" + this.cacheName + "\nException: " + ExceptionUtility.getStackTrace(ex));
            return returnCode;
        } finally {
            ce.skipValueSerialized = false;
        }

        try {
            rwLock.writeLock().lock();
            int dataSize = HashtableOnDisk.HTENTRY_OVERHEAD_SIZE + ce.serializedId.length + serializedDataLength + ce.serializedValue.length;
            if (dataSize % 512 != 0) { // size adjustment for 512 blocks
                dataSize = (dataSize / 512 + 1) * 512;
            }
            //if (this.testException) {
            //    throw new FileManagerException("*** Generate filemanager exception");
            //}
            int oldEntrySize = 0; // initialize the oldEntry size to 0
            HashtableEntry htEntry = null;
            if (ce.valueHashcode == 0 && null != ce.value) {
                ce.valueHashcode = ce.value.hashCode();
            }
            if (ce.timeLimit > 0) {
                htEntry = object_cache.put(ce.id, serializedData, serializedDataLength, ce.expirationTime, ce.validatorExpirationTime, ce.serializedId, ce.serializedValue,
                                           ce.valueHashcode, !HashtableOnDisk.ALIAS_ID); // LI4337-17  // put into HTOD
            } else {
                htEntry = object_cache.put(ce.id, serializedData, serializedDataLength, -1, ce.validatorExpirationTime, ce.serializedId, ce.serializedValue, ce.valueHashcode,
                                           !HashtableOnDisk.ALIAS_ID); // LI4337-17  // put into HTOD
            }
            //delete old entry from eviction table or insert into eviction table only if eviction policy is set
            if (this.cod.evictionPolicy != CacheConfig.EVICTION_NONE) {
                boolean bInsertEntry = true;
                if (htEntry != null) {
                    // check whether EvictionTable's attributes match or not
                    if ((ce.getId()).hashCode() == (htEntry.getKey()).hashCode() &&
                        ce.expirationTime == htEntry.expirationTime() &&
                        dataSize == htEntry.size()) {
                        // old entry exists and eviction's attributes match
                        // skip inserting the entry into EvictionTable because it already exists in EvictionTable
                        bInsertEntry = false;
                    } else {
                        // old entry exists but eviction's attributes do not match 
                        // then delete the entry from EvictionTable
                        synchronized (evictionTableMonitor) {
                            long expTime = htEntry.expirationTime();
                            if (expTime <= 0)
                                expTime = Long.MAX_VALUE;
                            EvictionTableEntry evt = EvictionTable.findAndRemove(expTime, (htEntry.getKey()).hashCode(), htEntry.size());
                            if (evt != null) {
                                if (tc.isDebugEnabled())
                                    Tr.debug(tc, "writeCacheEntry()", " **deleting** id=" + ce.id + " hc=" + evt.hashcode + " expirationTime=" + evt.expirationTime + " size="
                                                                      + evt.size);
                                evictionEntryPool.add(evt); // return evt to the pool
                            }
                        }
                    }
                }
                // if bInsertEntry boolean is true, insert the entry into EvictionTable. Else skip inserting.
                if (bInsertEntry == true) {
                    EvictionTableEntry evt = (EvictionTableEntry) evictionEntryPool.remove();
                    evt.hashcode = (ce.getId()).hashCode();
                    evt.expirationTime = ce.expirationTime;
                    if (evt.expirationTime <= 0)
                        evt.expirationTime = Long.MAX_VALUE;
                    evt.size = dataSize;
                    evt.id = ce.id; // use it for debug
                    synchronized (evictionTableMonitor) {
                        EvictionTable.insert(evt);
                    }
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "WriteCacheEntry()", "**adding** id=" + ce.id + " hc=" + evt.hashcode + " expirationTime=" + evt.expirationTime + " size=" + evt.size);
                }
            }
            // if htEntry is not null, it means the entry is overwritten
            if (htEntry != null) {
                if (tc.isDebugEnabled())
                    Tr.debug(tc, methodName, "cacheName=" + this.cacheName + " overwritten with id=" + ce.id);
                returnCode = NO_EXCEPTION_ENTRY_OVERWRITTEN;
                oldEntrySize = htEntry.size();
                returnToHashtableEntryPool(htEntry);
            }
            if (this.cod.enableCacheSizeInBytes) {
                this.cod.currentCacheSizeInBytes = this.cod.currentCacheSizeInBytes + dataSize - oldEntrySize;
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "WriteCacheEntry()", "**** id=" + ce.id + " size=" + dataSize + " currentCacheSizeInBytes" + this.cod.currentCacheSizeInBytes + " overhead="
                                                      + HashtableOnDisk.HTENTRY_OVERHEAD_SIZE + " idSize=" + ce.serializedId.length + " ceSize=" + serializedDataLength
                                                      + " valueSize=" + ce.serializedValue.length);
            }
            if (tc.isDebugEnabled())
                Tr.debug(tc, methodName, "cacheName=" + this.cacheName + " cacheSizeInBytes" + this.cod.currentCacheSizeInBytes + " newSize=" + dataSize + " oldSize="
                                         + oldEntrySize + " id=" + ce.id + " enable=" + this.cod.enableCacheSizeInBytes);
            this.cache.getCacheStatisticsListener().writeEntryToDisk(ce.id, dataSize);
            for (int i = 0; i < ce.aliasList.length; i++) {
                if (tc.isDebugEnabled())
                    Tr.debug(tc, methodName, "cacheName=" + this.cacheName + " adding alias with id=" + ce.id + " alias=" + ce.aliasList[i]);
                // alias id has no expiration time
                object_cache.put(ce.aliasList[i], ce.getIdObject(), -1, -1, -1, null, null, 0, HashtableOnDisk.ALIAS_ID);
                this.invalidationBuffer.remove(ce.aliasList[i], HTODInvalidationBuffer.EXPLICIT_BUFFER);
            }
        } catch (FileManagerException ex) {
            this.diskCacheException = ex;
            diskException = ex;
            returnCode = DISK_EXCEPTION;
        } catch (HashtableOnDiskException ex) {
            this.diskCacheException = ex;
            diskException = ex;
            returnCode = DISK_EXCEPTION;
        } catch (IOException ex) {
            diskException = ex;
            if (ex.getMessage().equals(DISK_CACHE_IN_GB_OVER_LIMIT_MSG)) {
                returnCode = DISK_SIZE_OVER_LIMIT_EXCEPTION;
            } else {
                this.diskCacheException = ex;
                returnCode = DISK_EXCEPTION;
            }
        } catch (Exception ex) {
            returnCode = OTHER_EXCEPTION;
            diskException = ex;
        } finally {
            rwLock.writeLock().unlock();
            if (returnCode != NO_EXCEPTION && returnCode != NO_EXCEPTION_ENTRY_OVERWRITTEN) {
                if (tc.isDebugEnabled())
                    Tr.debug(tc, methodName, "cacheName=" + this.cacheName + "\n Exception: " + ExceptionUtility.getStackTrace(diskException));
            }
            if (returnCode == DISK_EXCEPTION || returnCode == OTHER_EXCEPTION) {
                com.ibm.ws.ffdc.FFDCFilter.processException(diskException, "com.ibm.ws.cache.HTODDynacache.writeCacheEntry", "1239", this);
            }
        }

        return returnCode;
    }
22871
function(header, key, cert) {
        var parsedHeader;
        if (header) {
          if (!header.isBase64()) {
            throw new CError('missing header or wrong format').log();
          } else {
            parsedHeader = JSON.parse(forge.util.decode64(header));
            this.isModeAllowed.call(this, parsedHeader.payload.mode);
          }
          var Handshake      = app.class.Handshake,
              Authentication = app.class.Authentication,
              Authorization  = app.class.Authorization,
              mode           = parsedHeader.payload.mode,
              sid            = parsedHeader.payload.sid,
              result         = {};

          var options = {
            sid: sid,
            key: key || config.key,
            cert: cert || config.cert
          };
          switch (mode) {
            case 'handshake':
              result.header = new Handshake(options);
              break;
            case 'auth-init':
              result.header = new Authentication(options);
              break;
            default :
              result.header = new Authorization(options);
              break;
          }
          try {
            var ecryptedSecret = parsedHeader.payload.secret;
            if (ecryptedSecret) {
              var secret = result.header.keychain.decryptRsa(ecryptedSecret);
              result.header.setSecret(secret);
            }
            parsedHeader.content = result.header.decryptContent(parsedHeader.content);
          } catch (e) {
            throw new CError({
              body: {
                code: 'ImATeapot',
                message: 'unable to decrypt content',
                cause: e
              }
            }).log('body');
          }

          delete result.header;

          if (debug) {
            log.debug('%s parsed header', app.name);
            log.debug(parsedHeader);
          }
        }
        return parsedHeader;
      }
615568
private byte[] encodePKIPATH() throws CertificateEncodingException {

        ListIterator<X509Certificate> li = certs.listIterator(certs.size());
        try {
            DerOutputStream bytes = new DerOutputStream();
            // encode certs in reverse order (trust anchor to target)
            // according to PkiPath format
            while (li.hasPrevious()) {
                X509Certificate cert = li.previous();
                // check for duplicate cert
                if (certs.lastIndexOf(cert) != certs.indexOf(cert)) {
                    throw new CertificateEncodingException
                        ("Duplicate Certificate");
                }
                // get encoded certificates
                byte[] encoded = cert.getEncoded();
                bytes.write(encoded);
            }

            // Wrap the data in a SEQUENCE
            DerOutputStream derout = new DerOutputStream();
            derout.write(DerValue.tag_SequenceOf, bytes);
            return derout.toByteArray();

        } catch (IOException ioe) {
           throw new CertificateEncodingException("IOException encoding " +
                   "PkiPath data: " + ioe, ioe);
        }
    }
547357
private String getKey(Object key) {
        if (key == null) {
            throw new IllegalArgumentException("Cache key not be null");
        }

        return ObjectUtils.toString(key);
    }
948346
public static String getFirstResourceId(final CacheKey key) {
    try {
      if (key instanceof MultiCacheKey) {
        List<CacheKey> keys = ((MultiCacheKey) key).getCacheKeys();
        return secureHashKey(keys.get(0));
      } else {
        return secureHashKey(key);
      }
    } catch (UnsupportedEncodingException e) {
      // This should never happen. All VMs support UTF-8
      throw new RuntimeException(e);
    }
  }
428210
public synchronized boolean containsKey(CacheKey key) {
    Preconditions.checkNotNull(key);
    if (!mMap.containsKey(key)) {
      return false;
    }
    EncodedImage storedEncodedImage = mMap.get(key);
    synchronized (storedEncodedImage) {
      if (!EncodedImage.isValid(storedEncodedImage)) {
        // Reference is not valid, this means that someone cleared reference while it was still in
        // use. Log error
        // TODO: 3697790
        mMap.remove(key);
        FLog.w(
            TAG,
            "Found closed reference %d for key %s (%d)",
            System.identityHashCode(storedEncodedImage),
            key.getUriString(),
            System.identityHashCode(key));
        return false;
      }
      return true;
    }
  }
345872
function nusoap_wsdlcache($cache_dir='.', $cache_lifetime=0) {
		$this->fplock = array();
		$this->cache_dir = $cache_dir != '' ? $cache_dir : '.';
		$this->cache_lifetime = $cache_lifetime;
	}
1267248
function(apiKey, secretKey) {
  this._apiKey = apiKey;
  this._secretKey = secretKey;
  this._authentificate = new Buffer(apiKey + ':' + secretKey).toString('base64');
}
1002220
public static String getUniqueKey(X509Certificate cert) {
        // TBD - Would like to use public key instead of subject name, but
        // cert.getPublicKey().getEncoded() appears to return different
        // values for each call, using the same certificate??
        StringBuffer key = new StringBuffer("subjectDN:");
        key.append(cert.getSubjectX500Principal().getName()).append("issuerDN:").append(cert.getIssuerX500Principal().getName());
        // TODO::
        // return Base64Coder.base64Encode(getDigest(key.toString()));
        return null;
    }
523961
function ClientSSLSecurity(key, cert, ca, defaults) {
  if (key) {
    if(Buffer.isBuffer(key)) {
      this.key = key;
    } else if (typeof key === 'string') {
      this.key = fs.readFileSync(key);
    } else {
      throw new Error('key should be a buffer or a string!');
    }
  }

  if (cert) {
    if(Buffer.isBuffer(cert)) {
      this.cert = cert;
    } else if (typeof cert === 'string') {
      this.cert = fs.readFileSync(cert);
    } else {
      throw new Error('cert should be a buffer or a string!');
    }
  }

  if (ca) {
    if(Buffer.isBuffer(ca) || Array.isArray(ca)) {
      this.ca = ca;
    } else if (typeof ca === 'string') {
      this.ca = fs.readFileSync(ca);
    } else {
      defaults = ca;
      this.ca = null;
    }
  }

  this.defaults = {};
  _.merge(this.defaults, defaults);

  this.agent = null;
}
1248513
function saveX509($cert, $format = FILE_X509_FORMAT_PEM)
    {
        if (!is_array($cert) || !isset($cert['tbsCertificate'])) {
            return false;
        }

        switch (true) {
            // "case !$a: case !$b: break; default: whatever();" is the same thing as "if ($a && $b) whatever()"
            case !($algorithm = $this->_subArray($cert, 'tbsCertificate/subjectPublicKeyInfo/algorithm/algorithm')):
            case is_object($cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']):
                break;
            default:
                switch ($algorithm) {
                    case 'rsaEncryption':
                        $cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']
                            = base64_encode("\0" . base64_decode(preg_replace('#-.+-|[\r\n]#', '', $cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'])));
                        /* "[For RSA keys] the parameters field MUST have ASN.1 type NULL for this algorithm identifier."
                           -- https://tools.ietf.org/html/rfc3279#section-2.3.1

                           given that and the fact that RSA keys appear ot be the only key type for which the parameters field can be blank,
                           it seems like perhaps the ASN.1 description ought not say the parameters field is OPTIONAL, but whatever.
                         */
                        $cert['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['parameters'] = null;
                        // https://tools.ietf.org/html/rfc3279#section-2.2.1
                        $cert['signatureAlgorithm']['parameters'] = null;
                        $cert['tbsCertificate']['signature']['parameters'] = null;
                }
        }

        $asn1 = new File_ASN1();
        $asn1->loadOIDs($this->oids);

        $filters = array();
        $type_utf8_string = array('type' => FILE_ASN1_TYPE_UTF8_STRING);
        $filters['tbsCertificate']['signature']['parameters'] = $type_utf8_string;
        $filters['tbsCertificate']['signature']['issuer']['rdnSequence']['value'] = $type_utf8_string;
        $filters['tbsCertificate']['issuer']['rdnSequence']['value'] = $type_utf8_string;
        $filters['tbsCertificate']['subject']['rdnSequence']['value'] = $type_utf8_string;
        $filters['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['parameters'] = $type_utf8_string;
        $filters['signatureAlgorithm']['parameters'] = $type_utf8_string;
        $filters['authorityCertIssuer']['directoryName']['rdnSequence']['value'] = $type_utf8_string;
        //$filters['policyQualifiers']['qualifier'] = $type_utf8_string;
        $filters['distributionPoint']['fullName']['directoryName']['rdnSequence']['value'] = $type_utf8_string;
        $filters['directoryName']['rdnSequence']['value'] = $type_utf8_string;

        /* in the case of policyQualifiers/qualifier, the type has to be FILE_ASN1_TYPE_IA5_STRING.
           FILE_ASN1_TYPE_PRINTABLE_STRING will cause OpenSSL's X.509 parser to spit out random
           characters.
         */
        $filters['policyQualifiers']['qualifier']
            = array('type' => FILE_ASN1_TYPE_IA5_STRING);

        $asn1->loadFilters($filters);

        $this->_mapOutExtensions($cert, 'tbsCertificate/extensions', $asn1);
        $this->_mapOutDNs($cert, 'tbsCertificate/issuer/rdnSequence', $asn1);
        $this->_mapOutDNs($cert, 'tbsCertificate/subject/rdnSequence', $asn1);

        $cert = $asn1->encodeDER($cert, $this->Certificate);

        switch ($format) {
            case FILE_X509_FORMAT_DER:
                return $cert;
            // case FILE_X509_FORMAT_PEM:
            default:
                return "-----BEGIN CERTIFICATE-----\r\n" . chunk_split(base64_encode($cert), 64) . '-----END CERTIFICATE-----';
        }
    }