Tries to identify a PKCS12 container.
    The PFX PDU version is assumed to be v3.
    See: https://tools.ietf.org/html/rfc7292.
14050
def is_pkcs12(data):
    
    if isinstance(data, bytes):
        tlv = Tlv(data)
        if tlv.tag == 0x30:
            header = Tlv(tlv.value)
            return header.tag == 0x02 and header.value == b'\x03'
        return False
    else:
        return False
870102
def pkcs7_unpad(buf):
    # type: (bytes) -> bytes
    
    unpadder = cryptography.hazmat.primitives.padding.PKCS7(
        cryptography.hazmat.primitives.ciphers.
        algorithms.AES.block_size).unpadder()
    return unpadder.update(buf) + unpadder.finalize()
861417
def decode(self, pdu):
        """"""
        if _debug: APCI._debug("decode %r", pdu)

        PCI.update(self, pdu)

        # decode the first octet
        buff = pdu.get()

        # decode the APCI type
        self.apduType = (buff >> 4) & 0x0F

        if (self.apduType == ConfirmedRequestPDU.pduType):
            self.apduSeg = ((buff & 0x08) != 0)
            self.apduMor = ((buff & 0x04) != 0)
            self.apduSA  = ((buff & 0x02) != 0)
            buff = pdu.get()
            self.apduMaxSegs = (buff >> 4) & 0x07
            self.apduMaxResp = buff & 0x0F
            self.apduInvokeID = pdu.get()
            if self.apduSeg:
                self.apduSeq = pdu.get()
                self.apduWin = pdu.get()
            self.apduService = pdu.get()
            self.pduData = pdu.pduData

        elif (self.apduType == UnconfirmedRequestPDU.pduType):
            self.apduService = pdu.get()
            self.pduData = pdu.pduData

        elif (self.apduType == SimpleAckPDU.pduType):
            self.apduInvokeID = pdu.get()
            self.apduService = pdu.get()

        elif (self.apduType == ComplexAckPDU.pduType):
            self.apduSeg = ((buff & 0x08) != 0)
            self.apduMor = ((buff & 0x04) != 0)
            self.apduInvokeID = pdu.get()
            if self.apduSeg:
                self.apduSeq = pdu.get()
                self.apduWin = pdu.get()
            self.apduService = pdu.get()
            self.pduData = pdu.pduData

        elif (self.apduType == SegmentAckPDU.pduType):
            self.apduNak = ((buff & 0x02) != 0)
            self.apduSrv = ((buff & 0x01) != 0)
            self.apduInvokeID = pdu.get()
            self.apduSeq = pdu.get()
            self.apduWin = pdu.get()

        elif (self.apduType == ErrorPDU.pduType):
            self.apduInvokeID = pdu.get()
            self.apduService = pdu.get()
            self.pduData = pdu.pduData

        elif (self.apduType == RejectPDU.pduType):
            self.apduInvokeID = pdu.get()
            self.apduAbortRejectReason = pdu.get()

        elif (self.apduType == AbortPDU.pduType):
            self.apduSrv = ((buff & 0x01) != 0)
            self.apduInvokeID = pdu.get()
            self.apduAbortRejectReason = pdu.get()
            self.pduData = pdu.pduData

        else:
            raise DecodingError("invalid APDU type")
437235
def get_version_id(protocol_version):
    
    ver = registry.version_info.get(protocol_version)
    if ver:
        return ver.version_id
1103862
def get_from_ipfs_and_checkhash(ipfs_client, ipfs_hash_base58, validate=True):
    
    if validate:
        from snet_cli.resources.proto.unixfs_pb2 import Data
        from snet_cli.resources.proto.merckledag_pb2 import MerkleNode

        # No nice Python library to parse ipfs blocks, so do it ourselves.
        block_data = ipfs_client.block_get(ipfs_hash_base58)
        mn = MerkleNode()
        mn.ParseFromString(block_data)
        unixfs_data = Data()
        unixfs_data.ParseFromString(mn.Data)
        assert unixfs_data.Type == unixfs_data.DataType.Value('File'), "IPFS hash must be a file"
        data = unixfs_data.Data
        
        # multihash has a badly registered base58 codec, overwrite it...
        multihash.CodecReg.register('base58', base58.b58encode, base58.b58decode)
        # create a multihash object from our ipfs hash
        mh = multihash.decode(ipfs_hash_base58.encode('ascii'), 'base58')
        
        # Convenience method lets us directly use a multihash to verify data
        if not mh.verify(block_data):
            raise Exception("IPFS hash mismatch with data")
    else:
        data = ipfs_client.cat(ipfs_hash_base58)
    return data
1101200
def version(self):
        

        resp = self.call('version')

        for key in ('rpc_version', 'store_version'):
            resp[key] = int(resp[key])

        return resp
1307278
private static String toJavaCipherSuitePrefix(String protocolVersion) {
        final char c;
        if (protocolVersion == null || protocolVersion.isEmpty()) {
            c = 0;
        } else {
            c = protocolVersion.charAt(0);
        }

        switch (c) {
            case 'T':
                return "TLS";
            case 'S':
                return "SSL";
            default:
                return "UNKNOWN";
        }
    }
1175085
private Collection<? extends java.security.cert.Certificate>
        parseX509orPKCS7Cert(InputStream is)
        throws CertificateException, IOException
    {
        Collection<X509CertImpl> coll = new ArrayList<>();
        byte[] data = readOneBlock(is);
        if (data == null) {
            return new ArrayList<>(0);
        }
        try {
            PKCS7 pkcs7 = new PKCS7(data);
            X509Certificate[] certs = pkcs7.getCertificates();
            // certs are optional in PKCS #7
            if (certs != null) {
                return Arrays.asList(certs);
            } else {
                // no crls provided
                return new ArrayList<>(0);
            }
        } catch (ParsingException e) {
            while (data != null) {
                coll.add(new X509CertImpl(data));
                data = readOneBlock(is);
            }
        }
        return coll;
    }
799179
def identify_protocol(method, value):
    # type: (str, Union[str, RequestType]) -> str
    
    for protocol_name in PROTOCOLS:
        protocol = importlib.import_module(f"federation.protocols.{protocol_name}.protocol")
        if getattr(protocol, f"identify_{method}")(value):
            return protocol
    else:
        raise NoSuitableProtocolFoundError()
1281630
public static Map<String, Version> identify(ClassLoader classLoader) {
        if (classLoader == null) {
            classLoader = PlatformDependent.getContextClassLoader();
        }

        // Collect all properties.
        Properties props = new Properties();
        try {
            Enumeration<URL> resources = classLoader.getResources("META-INF/io.netty.versions.properties");
            while (resources.hasMoreElements()) {
                URL url = resources.nextElement();
                InputStream in = url.openStream();
                try {
                    props.load(in);
                } finally {
                    try {
                        in.close();
                    } catch (Exception ignore) {
                        // Ignore.
                    }
                }
            }
        } catch (Exception ignore) {
            // Not critical. Just ignore.
        }

        // Collect all artifactIds.
        Set<String> artifactIds = new HashSet<String>();
        for (Object o: props.keySet()) {
            String k = (String) o;

            int dotIndex = k.indexOf('.');
            if (dotIndex <= 0) {
                continue;
            }

            String artifactId = k.substring(0, dotIndex);

            // Skip the entries without required information.
            if (!props.containsKey(artifactId + PROP_VERSION) ||
                !props.containsKey(artifactId + PROP_BUILD_DATE) ||
                !props.containsKey(artifactId + PROP_COMMIT_DATE) ||
                !props.containsKey(artifactId + PROP_SHORT_COMMIT_HASH) ||
                !props.containsKey(artifactId + PROP_LONG_COMMIT_HASH) ||
                !props.containsKey(artifactId + PROP_REPO_STATUS)) {
                continue;
            }

            artifactIds.add(artifactId);
        }

        Map<String, Version> versions = new TreeMap<String, Version>();
        for (String artifactId: artifactIds) {
            versions.put(
                    artifactId,
                    new Version(
                            artifactId,
                            props.getProperty(artifactId + PROP_VERSION),
                            parseIso8601(props.getProperty(artifactId + PROP_BUILD_DATE)),
                            parseIso8601(props.getProperty(artifactId + PROP_COMMIT_DATE)),
                            props.getProperty(artifactId + PROP_SHORT_COMMIT_HASH),
                            props.getProperty(artifactId + PROP_LONG_COMMIT_HASH),
                            props.getProperty(artifactId + PROP_REPO_STATUS)));
        }

        return versions;
    }
27105
def _identify
    begin
      product = nil
      { "sfcb" => [ "root/interop", "CIM_ObjectManager" ],
        "pegasus" => [ "root/PG_Internal", "PG_ConfigSetting" ]
      }.each do |cimom, op|
        obj = objectpath *op
        @client.instances(obj).each do |inst|
          product = inst.Description || cimom
          break
        end
        break if product
      end
    rescue Sfcc::Cim::ErrorInvalidClass, Sfcc::Cim::ErrorInvalidNamespace
      raise "Unknown CIMOM"
    end
    product
  end
1043808
def pbkdf2_hex(data, salt, iterations=1000, keylen=24, hashfunc=None):
    """"""
    return hexlify_(pbkdf2_bin(data, salt, iterations, keylen, hashfunc))
533132
private void processOPCPackage(OPCPackage pkg) throws FormatNotUnderstoodException {
		LOG.debug("Processing OPCPackage in low footprint mode");
		// check if signature should be verified
		if (this.hocr.getVerifySignature()) {
				LOG.info("Verifying signature of document");
				SignatureConfig sic = new SignatureConfig();
				sic.setOpcPackage(pkg);
				SignatureInfo si = new SignatureInfo();
				si.setSignatureConfig(sic);
				if (!si.verifySignature()) {
						throw new FormatNotUnderstoodException("Cannot verify signature of OOXML (.xlsx) file: "+this.hocr.getFileName());
				} else {
					LOG.info("Successfully verifed first part signature of OXXML (.xlsx) file: "+this.hocr.getFileName());
				}
				Iterator<SignaturePart> spIter = si.getSignatureParts().iterator();
				 while (spIter.hasNext()) {
					 SignaturePart currentSP = spIter.next();
					 if (!(currentSP.validate())) {
						 throw new FormatNotUnderstoodException("Could not validate all signature parts for file: "+this.hocr.getFileName());
					 } else {
						 X509Certificate currentCertificate = currentSP.getSigner();
						 try {
							if ((this.hocr.getX509CertificateChain().size()>0) && (!CertificateChainVerificationUtil.verifyCertificateChain(currentCertificate, this.hocr.getX509CertificateChain()))) {
								 throw new FormatNotUnderstoodException("Could not validate signature part for principal \""+currentCertificate.getSubjectX500Principal().getName()+"\" : "+this.hocr.getFileName());
							 }
						} catch (CertificateException | NoSuchAlgorithmException | NoSuchProviderException
								| InvalidAlgorithmParameterException e) {
							LOG.error("Could not validate signature part for principal \""+currentCertificate.getSubjectX500Principal().getName()+"\" : "+this.hocr.getFileName(), e);
							 throw new FormatNotUnderstoodException("Could not validate signature part for principal \""+currentCertificate.getSubjectX500Principal().getName()+"\" : "+this.hocr.getFileName());
								
						}
					 }
				 }
				 LOG.info("Successfully verifed all signatures of OXXML (.xlsx) file: "+this.hocr.getFileName());
		}
		// continue in lowfootprint mode
		XSSFReader r;
		try {
			r = new XSSFReader( pkg );
		} catch (IOException | OpenXML4JException e) {
			LOG.error(e);
			throw new FormatNotUnderstoodException("Error cannot parse new Excel file (.xlsx)");
		}
		try {
			// read date format
			InputStream workbookDataXML = r.getWorkbookData();
			WorkbookDocument wd = WorkbookDocument.Factory.parse(workbookDataXML);
			this.isDate1904 = wd.getWorkbook().getWorkbookPr().getDate1904();

			
			// read shared string tables
			if (HadoopOfficeReadConfiguration.OPTION_LOWFOOTPRINT_PARSER_SAX.equalsIgnoreCase(this.hocr.getLowFootprintParser())) {
				this.pushSST = new ReadOnlySharedStringsTable(pkg);
			} else if (HadoopOfficeReadConfiguration.OPTION_LOWFOOTPRINT_PARSER_STAX.equalsIgnoreCase(this.hocr.getLowFootprintParser())) {
				List<PackagePart> pkgParts = pkg.getPartsByContentType(XSSFRelation.SHARED_STRINGS.getContentType());
				if (pkgParts.size()>0) {
					this.pullSST = new EncryptedCachedDiskStringsTable(pkgParts.get(0), this.hocr.getSstCacheSize(), this.hocr.getCompressSST(), this.ca, this.cm);			
				}
			}
			this.styles = r.getStylesTable();
			XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator)r.getSheetsData();
			int sheetNumber = 0;
			while (iter.hasNext()) {
				
				// check if we need to parse this sheet?
				boolean parse=false;
				if (this.sheets!=null) {
					for (int i=0;i<this.sheets.length;i++) {
						if (iter.getSheetName().equals(this.sheets[i])) {
							parse=true;
							break;
						}
					}
				} else {
					parse=true;
				}
				// sheet is supposed to be parsed
				if (parse) {
					
					InputStream rawSheetInputStream = iter.next();
					this.sheetNameList.add(iter.getSheetName());
					InputSource rawSheetInputSource = new InputSource(rawSheetInputStream);
					if (HadoopOfficeReadConfiguration.OPTION_LOWFOOTPRINT_PARSER_SAX.equalsIgnoreCase(this.hocr.getLowFootprintParser())) {
						this.event=true;
						LOG.info("Using SAX parser for low footprint Excel parsing");
						XMLReader sheetParser = SAXHelper.newXMLReader();
						XSSFEventParser xssfp = new XSSFEventParser(sheetNumber,iter.getSheetName(), this.spreadSheetCellDAOCache);
						
			            ContentHandler handler = new XSSFSheetXMLHandler(
			                  this.styles, iter.getSheetComments(), this.pushSST, xssfp, this.useDataFormatter, false);
			            sheetParser.setContentHandler(handler);
			            sheetParser.parse(rawSheetInputSource);
			            sheetNumber++;
					} else if (HadoopOfficeReadConfiguration.OPTION_LOWFOOTPRINT_PARSER_STAX.equalsIgnoreCase(this.hocr.getLowFootprintParser())) {
						LOG.info("Using STAX parser for low footprint Excel parsing");
						this.event=false;
						this.pullSheetInputList.add(rawSheetInputStream);
						this.pullSheetNameList.add(iter.getSheetName());
						// make shared string table available
						
						// everything else is in the getNext method
					} else {
						LOG.error("Unknown XML parser configured for low footprint mode: \""+this.hocr.getLowFootprintParser()+"\"");
						throw new FormatNotUnderstoodException("Unknown XML parser configured for low footprint mode: \""+this.hocr.getLowFootprintParser()+"\"");
					}

				}
						}
		} catch (InvalidFormatException | IOException e) {
			LOG.error(e);
			throw new FormatNotUnderstoodException("Error cannot parse new Excel file (.xlsx)");
		} catch (SAXException e) {
			LOG.error(e);
			throw new FormatNotUnderstoodException("Parsing Excel sheet in .xlsx format failed. Cannot read XML content");
		} catch (ParserConfigurationException e) {
			LOG.error(e);
			throw new FormatNotUnderstoodException("Parsing Excel sheet in .xlsx format failed. Cannot read XML content");
		} catch (XmlException e) {
			LOG.error(e);
			throw new FormatNotUnderstoodException("Parsing Excel sheet in .xlsx format failed. Cannot read XML content");
		}
		 // check skipping of additional lines
		for (int i=0;i<this.hocr.getSkipLines();i++) {
			this.getNext();
		}
		 // check header
		 if (this.hocr.getReadHeader()) {

			 LOG.debug("Reading header...");
			 Object[] firstRow = this.getNext();
			 if (firstRow!=null) {
				 this.header=new String[firstRow.length];
				 for (int i=0;i<firstRow.length;i++) {
					 if ((firstRow[i]!=null) && (!"".equals(((SpreadSheetCellDAO)firstRow[i]).getFormattedValue()))) {
						 this.header[i]=((SpreadSheetCellDAO)firstRow[i]).getFormattedValue();
					 }
				 }
				 this.header=MSExcelParser.sanitizeHeaders(this.header, this.hocr.getColumnNameRegex(), this.hocr.getColumnNameReplace());
			 } else {
				 this.header=new String[0];
			 }
		 }
		 this.headerParsed=true;
		
	}
450122
@Provides
	@Singleton
	@JFunkVersion
	protected String providePerfLoadVersion() {
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		InputStream is = loader.getResourceAsStream("com/mgmtp/jfunk/common/version.txt");
		try {
			return IOUtils.toString(is, "UTF-8");
		} catch (IOException ex) {
			throw new IllegalStateException("Could not read jFunk version.", ex);
		} finally {
			IOUtils.closeQuietly(is);
		}
	}
1121331
def get_hpkp_pin(cls, certificate: cryptography.x509.Certificate) -> str:
        
        return b64encode(cls.get_public_key_sha256(certificate)).decode('utf-8')
638009
def is_driver(self):
        

        # Checking that the ImageBase field of the OptionalHeader is above or
        # equal to 0x80000000 (that is, whether it lies in the upper 2GB of
        # the address space, normally belonging to the kernel) is not a
        # reliable enough indicator.  For instance, PEs that play the invalid
        # ImageBase trick to get relocated could be incorrectly assumed to be
        # drivers.
         
        # This is not reliable either...
        #   
        # if any( (section.Characteristics & SECTION_CHARACTERISTICS['IMAGE_SCN_MEM_NOT_PAGED']) for section in self.sections ):
        #    return True
            
        if hasattr(self, 'DIRECTORY_ENTRY_IMPORT'):
            
            # If it imports from "ntoskrnl.exe" or other kernel components it should be a driver
            #
            if set( ('ntoskrnl.exe', 'hal.dll', 'ndis.sys', 'bootvid.dll', 'kdcom.dll' ) ).intersection( [ imp.dll.lower() for imp in self.DIRECTORY_ENTRY_IMPORT ] ):
                return True
                
        return False
540369
public static base_response convert(nitro_service client, sslpkcs12 resource) throws Exception {
		sslpkcs12 convertresource = new sslpkcs12();
		convertresource.outfile = resource.outfile;
		convertresource.Import = resource.Import;
		convertresource.pkcs12file = resource.pkcs12file;
		convertresource.des = resource.des;
		convertresource.des3 = resource.des3;
		convertresource.export = resource.export;
		convertresource.certfile = resource.certfile;
		convertresource.keyfile = resource.keyfile;
		convertresource.password = resource.password;
		convertresource.pempassphrase = resource.pempassphrase;
		return convertresource.perform_operation(client,"convert");
	}