//////////////////////////// PBES1 RFC8018 Section 6.1.1
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
  };
}
1238121
func PBPeersToPeerInfos(pbps []*Message_Peer) []*pstore.PeerInfo {
	peers := make([]*pstore.PeerInfo, 0, len(pbps))
	for _, pbp := range pbps {
		peers = append(peers, PBPeerToPeerInfo(pbp))
	}
	return peers
}
437796
@Override
  public final byte[] calculateSha1(final byte[] pPublicKey) throws Exception {
    Digest sha1 = new SHA1Digest();
    sha1.update(pPublicKey, 0, pPublicKey.length);
    byte[] digest = new byte[sha1.getDigestSize()];
    sha1.doFinal(digest, 0);
    return digest;
  }
872463
func (r *PEXReactor) crawlPeers(addrs []*p2p.NetAddress) {
	now := time.Now()

	for _, addr := range addrs {
		peerInfo, ok := r.crawlPeerInfos[addr.ID]

		// Do not attempt to connect with peers we recently crawled.
		if ok && now.Sub(peerInfo.LastCrawled) < minTimeBetweenCrawls {
			continue
		}

		// Record crawling attempt.
		r.crawlPeerInfos[addr.ID] = crawlPeerInfo{
			Addr:        addr,
			LastCrawled: now,
		}

		err := r.Switch.DialPeerWithAddress(addr, false)
		if err != nil {
			if _, ok := err.(p2p.ErrCurrentlyDialingOrExistingAddress); ok {
				continue
			}

			r.Logger.Error("Dialing failed", "addr", addr, "err", err)
			markAddrInBookBasedOnErr(addr, r.book, err)
			continue
		}

		peer := r.Switch.Peers().Get(addr.ID)
		if peer != nil {
			r.RequestAddrs(peer)
		}
	}
}
1021520
def rfc6979_ecdsa_nonce(hash, privkey)
      raise ArgumentError, "Hash must be 32 bytes long" if hash.bytesize != 32
      raise ArgumentError, "Private key must be 32 bytes long" if privkey.bytesize != 32

      autorelease do |pool|
        order = self.group_order

        # Step 3.2.a. hash = H(message). Already performed by the caller.

        # Step 3.2.b. V = 0x01 0x01 0x01 ... 0x01 (32 bytes equal 0x01)
        v = "\x01".b*32

        # Step 3.2.c. K = 0x00 0x00 0x00 ... 0x00 (32 bytes equal 0x00)
        k = "\x00".b*32

        # Step 3.2.d. K = HMAC-SHA256(key: K, data: V || 0x00 || int2octets(privkey) || bits2octets(hash))
        h1 = pool.new_bn(hash)
        BN_div(nil, h1, h1, order, pool.bn_ctx) # h1 = h1 % order
        h1data = data_from_bn(h1, min_length: 32)
        k = BTC.hmac_sha256(key: k, data: v + "\x00".b + privkey + h1data)

        # Step 3.2.e. V = HMAC-SHA256(key: K, data: V)
        v = BTC.hmac_sha256(key: k, data: v)

        # Step 3.2.f. K = HMAC-SHA256(key: K, data: V || 0x01 || int2octets(privkey) || bits2octets(hash))
        k = BTC.hmac_sha256(key: k, data: v + "\x01".b + privkey + h1data)

        # Step 3.2.g. V = HMAC-SHA256(key: K, data: V)
        v = BTC.hmac_sha256(key: k, data: v)

        # Step 3.2.h.
        zero32 = "\x00".b*32
        10000.times do
          t = BTC.hmac_sha256(key: k, data: v)
          tn = pool.new_bn(t)
          if BN_cmp(tn, order) < 0
            nonce = data_from_bn(tn, min_length: 32)
            if nonce != zero32
              return nonce
            end
          end
          # Note: the probability of not succeeding at the first try is about 2^-127.
          k = BTC.hmac_sha256(key: k, data: v + zero32)
          v = BTC.hmac_sha256(key: k, data: v)
        end
        # we generated 10000 numbers, none of them is good -> fail.
        raise "Cannot find any good ECDSA nonce after 10000 iterations of RFC6979."
      end
    end
415184
@Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "checkServerTrusted");

        Map<String, Object> currentConnectionInfo = ThreadManager.getInstance().getOutboundConnectionInfoInternal();
        if (currentConnectionInfo != null) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "original peerHost: " + peerHost);
                Tr.debug(tc, "currentConnectionInfo: " + currentConnectionInfo);
            }
            peerHost = (String) currentConnectionInfo.get(Constants.CONNECTION_INFO_REMOTE_HOST);
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "current peerHost: " + peerHost);
        } else {
            currentConnectionInfo = extendedInfo;
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "currentConnectionInfo from extendedInfo: " + currentConnectionInfo);
        }

        extendedInfo = JSSEHelper.getInstance().getOutboundConnectionInfo();
        if (extendedInfo != null)
            peerHost = (String) extendedInfo.get(Constants.CONNECTION_INFO_REMOTE_HOST);

        // if we do not have host and port just go ahead and default it to unknown
        // to avoid null's
        if (peerHost == null || 0 == peerHost.length()) {
            peerHost = "unknown";
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Target host: " + peerHost);
            for (int j = 0; j < chain.length; j++) {
                Tr.debug(tc, "Certificate information:");
                Tr.debug(tc, "  Subject DN: " + chain[j].getSubjectDN());
                Tr.debug(tc, "  Issuer DN: " + chain[j].getIssuerDN());
                Tr.debug(tc, "  Serial number: " + chain[j].getSerialNumber());
            }
        }

        for (int i = 0; i < tm.length; i++) {
            if (tm[i] != null && tm[i] instanceof X509TrustManager) {
                // skip the default trust manager if configured to do so.
                try {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                        Tr.debug(tc, "Delegating to X509TrustManager: " + tm[i].getClass().getName());
                    ((X509TrustManager) tm[i]).checkServerTrusted(chain, authType);
                } catch (CertificateException e) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                        Tr.debug(tc, "Certificate Exception occurred: " + e.getMessage());

                    // if the reason for the CertificateException is due to
                    // an expired date, don't accept it.
                    boolean dateValid = checkIfExpiredBeforeOrAfter(chain);
                    if (!dateValid) {
                        throw e;
                    }

                    try {
                        // If this is a client process then we may prompt the user to accept the signer certificate
                        if (!isServer) {
                            if (!autoAccept) {
                                // prompt user
                                if (userAcceptedPrompt(chain)) {
                                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                                        Tr.debug(tc, "prompt user - adding certificate to the truststore.");
                                    setCertificateToTruststore(chain);
                                } else {
                                    printClientHandshakeError(config, tsFile, e, chain);
                                    throw e;
                                }

                            } else {
                                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                                    Tr.debug(tc, "autoacceptsigner - adding certificate to the truststore.");
                                setCertificateToTruststore(chain);
                            }
                        } else {
                            // IBM JDK will throw the exception in obfuscated code, get the cause
                            Exception excpt = e;
                            if (excpt.getClass().toString().startsWith("class com.ibm.jsse2")) {
                                excpt = (Exception) excpt.getCause();
                            }

                            // This the server print a message and rethrow the exception
                            FFDCFilter.processException(excpt, getClass().getName(), "checkServerTrusted", this, new Object[] { chain, authType });
                            printClientHandshakeError(config, tsFile, e, chain);
                            throw excpt;
                        }
                    } catch (Exception ex)
                    {
                        throw new CertificateException(ex.getMessage());
                    }
                }
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, "Server is trusted by all X509TrustManagers.");
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "checkServerTrusted");
    }
363766
final void buildBloomFilterForBucket(int bucketInSegmentPos, MemorySegment bucket, HashPartition<BT, PT> p) {
		final int count = bucket.getShort(bucketInSegmentPos + HEADER_COUNT_OFFSET);
		if (count <= 0) {
			return;
		}

		int[] hashCodes = new int[count];
		// As the hashcode and bloom filter occupy same bytes, so we read all hashcode out at first and then write back to bloom filter.
		for (int i = 0; i < count; i++) {
			hashCodes[i] = bucket.getInt(bucketInSegmentPos + BUCKET_HEADER_LENGTH + i * HASH_CODE_LEN);
		}
		this.bloomFilter.setBitsLocation(bucket, bucketInSegmentPos + BUCKET_HEADER_LENGTH);
		for (int hashCode : hashCodes) {
			this.bloomFilter.addHash(hashCode);
		}
		buildBloomFilterForExtraOverflowSegments(bucketInSegmentPos, bucket, p);
	}
268060
@Override
    protected int readBytesWireFormat ( byte[] buffer, int bufferIndex ) throws SMBProtocolDecodingException {
        int start = bufferIndex;
        int structureSize = SMBUtil.readInt2(buffer, bufferIndex);
        if ( structureSize == 9 ) {
            return super.readErrorResponse(buffer, bufferIndex);
        }
        else if ( structureSize != 49 ) {
            throw new SMBProtocolDecodingException("Expected structureSize = 49");
        }
        bufferIndex += 4;
        this.ctlCode = SMBUtil.readInt4(buffer, bufferIndex);
        bufferIndex += 4;

        this.fileId = new byte[16];
        System.arraycopy(buffer, bufferIndex, this.fileId, 0, 16);
        bufferIndex += 16;

        int inputOffset = SMBUtil.readInt4(buffer, bufferIndex) + getHeaderStart();
        bufferIndex += 4;

        int inputCount = SMBUtil.readInt4(buffer, bufferIndex);
        bufferIndex += 4;

        int outputOffset = SMBUtil.readInt4(buffer, bufferIndex) + getHeaderStart();
        bufferIndex += 4;

        int outputCount = SMBUtil.readInt4(buffer, bufferIndex);
        bufferIndex += 4;

        this.ioctlFlags = SMBUtil.readInt4(buffer, bufferIndex);
        bufferIndex += 4;
        bufferIndex += 4; // Reserved2

        this.inputData = createInputDecodable();
        this.outputData = this.outputBuffer == null ? createOutputDecodable() : null;

        if ( this.inputData != null ) {
            this.inputData.decode(buffer, inputOffset, inputCount);
        }
        bufferIndex = Math.max(inputOffset + inputCount, bufferIndex);

        if ( this.outputBuffer != null ) {
            if ( outputCount > this.outputBuffer.length ) {
                throw new SMBProtocolDecodingException("Output length exceeds buffer size");
            }
            System.arraycopy(buffer, outputOffset, this.outputBuffer, 0, outputCount);
        }
        else if ( this.outputData != null ) {
            this.outputData.decode(buffer, outputOffset, outputCount);
        }
        this.outputLength = outputCount;
        bufferIndex = Math.max(outputOffset + outputCount, bufferIndex);
        return bufferIndex - start;
    }
1113651
private IoBuffer encodeProxyRequestPacket(final SocksProxyRequest request)
            throws UnsupportedEncodingException {
        int len = 6;
        InetSocketAddress adr = request.getEndpointAddress();
        byte addressType = 0;
        byte[] host = null;
        
        if (adr != null && !adr.isUnresolved()) {
            if (adr.getAddress() instanceof Inet6Address) {
                len += 16;
                addressType = SocksProxyConstants.IPV6_ADDRESS_TYPE;
            } else if (adr.getAddress() instanceof Inet4Address) {
                len += 4;
                addressType = SocksProxyConstants.IPV4_ADDRESS_TYPE;
            }
        } else {
            host = request.getHost() != null ? 
                    request.getHost().getBytes("ASCII") : null;

            if (host != null) {
                len += 1 + host.length;
                addressType = SocksProxyConstants.DOMAIN_NAME_ADDRESS_TYPE;
            } else {
                throw new IllegalArgumentException("SocksProxyRequest object " +
                        "has no suitable endpoint information");
            }
        }
        
        IoBuffer buf = IoBuffer.allocate(len);

        buf.put(request.getProtocolVersion());
        buf.put(request.getCommandCode());
        buf.put((byte) 0x00); // Reserved
        buf.put(addressType);

        if (host == null) {
            buf.put(request.getIpAddress());
        } else {
            buf.put((byte) host.length);
            buf.put(host);            
        }

        buf.put(request.getPort());

        return buf;
    }
756044
func addBytesParts(ctx context.Context, bs blobserver.StatReceiver, dst *[]BytesPart, spans []span, parent *uploadBytesFuture) {
	for _, sp := range spans {
		if len(sp.children) == 1 && sp.children[0].isSingleBlob() {
			// Remove an occasional useless indirection of
			// what would become a bytes schema blob
			// pointing to a single blobref.  Just promote
			// the blobref child instead.
			child := sp.children[0]
			*dst = append(*dst, BytesPart{
				BlobRef: child.br,
				Size:    uint64(child.size()),
			})
			sp.children = nil
		}
		if len(sp.children) > 0 {
			childrenSize := int64(0)
			for _, cs := range sp.children {
				childrenSize += cs.size()
			}
			future := uploadBytes(ctx, bs, newBytes(), childrenSize, sp.children)
			parent.children = append(parent.children, future)
			*dst = append(*dst, BytesPart{
				BytesRef: future.BlobRef(),
				Size:     uint64(childrenSize),
			})
		}
		if sp.from == sp.to {
			panic("Shouldn't happen. " + fmt.Sprintf("weird span with same from & to: %#v", sp))
		}
		*dst = append(*dst, BytesPart{
			BlobRef: sp.br,
			Size:    uint64(sp.to - sp.from),
		})
	}
}
1255461
function pton6(addr, dest, index = 0) {
  if (typeof addr !== 'string') {
    throw new TypeError('Argument 1 should be a string.')
  }

  if (addr.length <= 0) {
    einval()
  }

  const isbuffer = Buffer.isBuffer(dest)
  const endp = index + IPV6_OCTETS

  if (isbuffer) {
    if (endp > dest.length) {
      throw new Error('Too small target buffer.')
    }
  }

  const buf = isbuffer ? dest : Buffer.allocUnsafe(IPV6_OCTETS)

  let i = 0
  let colonp = null
  let seenDigits = 0
  let val = 0
  let curtok = 0
  let ch = 0

  if (addr[i] === ':') {
    if (addr.length >= 2 && addr[++i] !== ':') {
      einval()
    }
  }

  curtok = i

  while ((ch = i++) < addr.length) {
    const char = code(addr[ch])

    if (isDigit(char) || isLetter16(char)) {
      val <<= 4

      if (isDigit(char)) {
        val |= char - CHAR0
      } else if (isLetter16Low(char)) {
        val |= char - CHARa + 10
      } else if (isLetter16Up(char)) {
        val |= char - CHARA + 10
      }

      if (++seenDigits > 4) {
        einval()
      }
    } else if (char === CHARCOLON) {
      curtok = i

      // If it's second colon in pair.
      if (seenDigits === 0) {
        // Only one colon pair allowed.
        if (colonp !== null) {
          einval()
        }

        colonp = index
        continue
      } else if (i >= addr.length) {
        einval()
      }

      if (index + 2 > endp) {
        einval()
      }

      buf[index++] = (val >> 8) & 0xFF
      buf[index++] = val & 0xFF

      seenDigits = 0
      val = 0
    } else if (char === CHARPOINT) {
      pton4(addr.slice(curtok), buf, index)
      index += IPV4_OCTETS
      seenDigits = 0
      break
    } else {
      einval()
    }
  }

  // Handle last pair.
  if (seenDigits > 0) {
    if (index + 2 > endp) {
      einval()
    }

    buf[index++] = (val >> 8) & 0xFF
    buf[index++] = val & 0xFF
  }

  if (colonp !== null) {
    const n = index - colonp

    if (index === endp) {
      einval()
    }

    buf.copyWithin(endp - n, colonp, colonp + n)
    fill(buf, 0, colonp, endp - n)
  }

  return buf
}
981559
function convertToZipkinSpan(span) {
  const result = {};
  result.traceId = utility.md5(span.traceId);
  result.parentId = span.parentSpanId;
  result.id = span.spanId;
  result.name = span.name;
  // it's microseconds
  result.timestamp = span.startTime * 1000;
  // it's microseconds
  result.duration = (span.finishTime - span.startTime) * 1000;
  result.tags = span.getTags();

  result.localEndpoint = {
    serviceName: span.getTag('appname'),
    ipv4: span.getTag('local.ipv4'),
    ipv6: span.getTag('local.ipv6'),
    port: span.getTag('local.port'),
  };

  let kind = span.getTag('span.kind');
  if (kind) {
    kind = kind.toUpperCase();
  }
  if ([ 'CLIENT', 'SERVER', 'PRODUCER', 'CONSUMER' ].includes(kind)) {
    result.kind = kind;
    result.remoteEndpoint = {
      serviceName: span.getTag('peer.service'),
      ipv6: span.getTag('peer.ipv6'),
      ipv4: span.getTag('peer.ipv4'),
      port: span.getTag('peer.port'),
    };
  }

  result.annotations = [];
  result.debug = false;
  result.shared = false;
  return result;
}
284504
private void parseIPv4(String name) throws IOException {

        // Parse name into byte-value address components
        int slashNdx = name.indexOf('/');
        if (slashNdx == -1) {
            address = InetAddress.getByName(name).getAddress();
        } else {
            address = new byte[8];

            // parse mask
            byte[] mask = InetAddress.getByName
                (name.substring(slashNdx+1)).getAddress();

            // parse base address
            byte[] host = InetAddress.getByName
                (name.substring(0, slashNdx)).getAddress();

            System.arraycopy(host, 0, address, 0, 4);
            System.arraycopy(mask, 0, address, 4, 4);
        }
    }
476405
@Override
    protected int readBytesWireFormat ( byte[] buffer, int bufferIndex ) throws SMBProtocolDecodingException {
        int start = bufferIndex;
        int structureSize = SMBUtil.readInt2(buffer, bufferIndex);

        if ( structureSize != 9 ) {
            throw new SMBProtocolDecodingException("Expected structureSize = 9");
        }

        int bufferOffset = SMBUtil.readInt2(buffer, bufferIndex + 2) + getHeaderStart();
        bufferIndex += 4;
        int bufferLength = SMBUtil.readInt4(buffer, bufferIndex);
        bufferIndex += 4;

        // bufferIndex = bufferOffset;

        List<FileEntry> infos = new ArrayList<>();
        do {
            FileBothDirectoryInfo cur = createFileInfo();
            if ( cur == null ) {
                break;
            }
            cur.decode(buffer, bufferIndex, bufferLength);
            infos.add(cur);
            int nextEntryOffset = cur.getNextEntryOffset();
            if ( nextEntryOffset > 0 ) {
                bufferIndex += nextEntryOffset;
            }
            else {
                break;
            }
        }
        while ( bufferIndex < bufferOffset + bufferLength );
        this.results = infos.toArray(new FileEntry[infos.size()]);
        return bufferIndex - start;
    }
1201391
func (c *Clientset) NodeV1beta1() nodev1beta1.NodeV1beta1Interface {
	return &fakenodev1beta1.FakeNodeV1beta1{Fake: &c.Fake}
}
83794
@Override
    protected int readBytesWireFormat ( byte[] buffer, int bufferIndex ) throws SMBProtocolDecodingException {
        int start = bufferIndex;
        int structureSize = SMBUtil.readInt2(buffer, bufferIndex);
        if ( structureSize == 9 ) {
            return this.readErrorResponse(buffer, bufferIndex);
        }
        else if ( structureSize != 17 ) {
            throw new SMBProtocolDecodingException("Expected structureSize = 17");
        }

        short dataOffset = buffer[ bufferIndex + 2 ];
        bufferIndex += 4;
        this.dataLength = SMBUtil.readInt4(buffer, bufferIndex);
        bufferIndex += 4;
        this.dataRemaining = SMBUtil.readInt4(buffer, bufferIndex);
        bufferIndex += 4;
        bufferIndex += 4; // Reserved2

        int dataStart = getHeaderStart() + dataOffset;

        if ( this.dataLength + this.outputBufferOffset > this.outputBuffer.length ) {
            throw new SMBProtocolDecodingException("Buffer to small for read response");
        }
        System.arraycopy(buffer, dataStart, this.outputBuffer, this.outputBufferOffset, this.dataLength);
        bufferIndex = Math.max(bufferIndex, dataStart + this.dataLength);
        return bufferIndex - start;
    }
539405
byte[] getEncoded() {
		byte[] peerHostBytes = (peerHost == null ? Bytes.EMPTY_BYTES : peerHost.getBytes());
		byte[] peerCertsBytes = encodeCerts(peerCertificates);
		byte[] localCertsBytes = encodeCerts(localCertificates);
		int idLen = id.length;
		int hostLen = peerHostBytes.length;
		int peerCertsLen = peerCertsBytes.length;
		int localCertsLen = localCertsBytes.length;
		byte[] b = new byte[12 + idLen + hostLen + peerCertsLen + localCertsLen];
		b[0] = (byte) idLen;
		b[1] = (byte) hostLen;
		Bytes.setShort(peerCertsLen, b, 2);
		Bytes.setShort(localCertsLen, b, 4);
		System.arraycopy(id, 0, b, 6, id.length);
		Integer cipherId_ = cipherName2Id.get(cipherSuite);
		Bytes.setShort(cipherId_ == null ? 0 : cipherId_.intValue(), b, 6 + idLen);
		Integer ver_ = proto2Ver.get(protocol);
		Bytes.setShort(ver_ == null ? -1 : ver_.intValue(), b, 8 + idLen);
		System.arraycopy(peerHostBytes, 0, b, 10 + idLen, hostLen);
		Bytes.setShort(peerPort, b, 10 + idLen + hostLen);
		System.arraycopy(peerCertsBytes, 0, b, 12 + idLen + hostLen, peerCertsLen);
		System.arraycopy(localCertsBytes, 0, b,
				12 + idLen + hostLen + peerCertsLen, localCertsLen);
		return b;
	}