从加密字符串转换

@param encryptedXml
@param wxCpConfigStorage
@param timestamp
@param nonce
@param msgSignature
@return
500143
public static WxCpXmlMessage fromEncryptedXml(
      String encryptedXml,
      WxCpConfigStorage wxCpConfigStorage,
      String timestamp, String nonce, String msgSignature) {
    WxCpCryptUtil cryptUtil = new WxCpCryptUtil(wxCpConfigStorage);
    String plainText = cryptUtil.decrypt(msgSignature, timestamp, nonce, encryptedXml);
    return fromXml(plainText);
  }
800007
public CMSEnvelopedData encode(final byte[] messageData)
            throws MessageEncodingException {
        LOGGER.debug("Encoding pkcsPkiEnvelope");
        CMSEnvelopedDataGenerator edGenerator = new CMSEnvelopedDataGenerator();
        CMSTypedData envelopable = new CMSProcessableByteArray(messageData);
        RecipientInfoGenerator recipientGenerator;
        try {
            recipientGenerator = new JceKeyTransRecipientInfoGenerator(
                    recipient);
        } catch (CertificateEncodingException e) {
            throw new MessageEncodingException(e);
        }
        edGenerator.addRecipientInfoGenerator(recipientGenerator);
        LOGGER.debug(
                "Encrypting pkcsPkiEnvelope using key belonging to [dn={}; serial={}]",
                recipient.getSubjectDN(), recipient.getSerialNumber());

        OutputEncryptor encryptor;
        try {
            encryptor = new JceCMSContentEncryptorBuilder(encAlgId).build();
        } catch (CMSException e) {
            throw new MessageEncodingException(e);
        }
        try {
            CMSEnvelopedData pkcsPkiEnvelope = edGenerator.generate(
                    envelopable, encryptor);

            LOGGER.debug("Finished encoding pkcsPkiEnvelope");
            return pkcsPkiEnvelope;
        } catch (CMSException e) {
            throw new MessageEncodingException(e);
        }
    }
3892
public function decryptMsg($msgSignature, $nonce, $timestamp, $postXML)
    {
        try {
            $array = XML::parse($postXML);
        } catch (BaseException $e) {
            throw new EncryptionException('Invalid xml.', EncryptionException::ERROR_PARSE_XML);
        }

        $encrypted = $array['Encrypt'];

        $signature = $this->getSHA1($this->token, $timestamp, $nonce, $encrypted);

        if ($signature !== $msgSignature) {
            throw new EncryptionException('Invalid Signature.', EncryptionException::ERROR_INVALID_SIGNATURE);
        }

        return XML::parse($this->decrypt($encrypted, $this->id));
    }
793934
public static boolean verifyTimestampCertificates(TimeStampToken ts, KeyStore keystore, String provider) {
        if (provider == null)
            provider = "BC";
        try {
            for (Enumeration aliases = keystore.aliases(); aliases.hasMoreElements();) {
                try {
                    String alias = (String)aliases.nextElement();
                    if (!keystore.isCertificateEntry(alias))
                        continue;
                    X509Certificate certStoreX509 = (X509Certificate)keystore.getCertificate(alias);
                    SignerInformationVerifier siv = new JcaSimpleSignerInfoVerifierBuilder().setProvider(provider).build(certStoreX509);
                    ts.validate(siv);
                    return true;
                }
                catch (Exception ex) {
                }
            }
        }
        catch (Exception e) {
        }
        return false;
    }
1145868
public String encrypt(String plainText) {
    // 加密
    String encryptedXml = encrypt(genRandomStr(), plainText);

    // 生成安全签名
    String timeStamp = timeStamp = Long.toString(System.currentTimeMillis() / 1000l);
    String nonce = genRandomStr();

    try {
      String signature = SHA1.gen(token, timeStamp, nonce, encryptedXml);
      String result = generateXml(encryptedXml, signature, timeStamp, nonce);
      return result;
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException(e);
    }
  }
399103
function write_ws_xml_protection(sp) {
	// algorithmName, hashValue, saltValue, spinCountpassword
	var o = ({sheet:1});
	var deffalse = ["objects", "scenarios", "selectLockedCells", "selectUnlockedCells"];
	var deftrue = [
		"formatColumns", "formatRows", "formatCells",
		"insertColumns", "insertRows", "insertHyperlinks",
		"deleteColumns", "deleteRows",
		"sort", "autoFilter", "pivotTables"
	];
	deffalse.forEach(function(n) { if(sp[n] != null && sp[n]) o[n] = "1"; });
	deftrue.forEach(function(n) { if(sp[n] != null && !sp[n]) o[n] = "0"; });
	/* TODO: algorithm */
	if(sp.password) o.password = crypto_CreatePasswordVerifier_Method1(sp.password).toString(16).toUpperCase();
	return writextag('sheetProtection', null, o);
}
791241
def _encode_msg(self, start_pos, offset, timestamp, key, value,
                    attributes=0):
        
        magic = self._magic
        buf = self._buffer
        pos = start_pos

        # Write key and value
        pos += self.KEY_OFFSET_V0 if magic == 0 else self.KEY_OFFSET_V1

        if key is None:
            struct.pack_into(">i", buf, pos, -1)
            pos += self.KEY_LENGTH
        else:
            key_size = len(key)
            struct.pack_into(">i", buf, pos, key_size)
            pos += self.KEY_LENGTH
            buf[pos: pos + key_size] = key
            pos += key_size

        if value is None:
            struct.pack_into(">i", buf, pos, -1)
            pos += self.VALUE_LENGTH
        else:
            value_size = len(value)
            struct.pack_into(">i", buf, pos, value_size)
            pos += self.VALUE_LENGTH
            buf[pos: pos + value_size] = value
            pos += value_size
        length = (pos - start_pos) - self.LOG_OVERHEAD

        # Write msg header. Note, that Crc will be updated later
        if magic == 0:
            self.HEADER_STRUCT_V0.pack_into(
                buf, start_pos,
                offset, length, 0, magic, attributes)
        else:
            self.HEADER_STRUCT_V1.pack_into(
                buf, start_pos,
                offset, length, 0, magic, attributes, timestamp)

        # Calculate CRC for msg
        crc_data = memoryview(buf)[start_pos + self.MAGIC_OFFSET:]
        crc = calc_crc32(crc_data)
        struct.pack_into(">I", buf, start_pos + self.CRC_OFFSET, crc)
        return crc
733922
public function encryptMsg($xml)
    {
        $appId          = Api::getAppId();
        $token          = Api::getToken();
        $encodingAesKey = Api::getEncoding_Aes_Key();

        if (empty($token) || !$token || empty($encodingAesKey) || !$encodingAesKey) {
            return $xml;
        }

        $timeStamp = time();
        $nonce     = $this->getRandomStr();

        $pc         = new WXBizMsgCrypt($token, $encodingAesKey, $appId);
        $encryptMsg = '';
        $errCode    = $pc->encryptMsg($xml, $timeStamp, $nonce, $encryptMsg);
        if ($errCode == 0) {
            return $encryptMsg;
        } else {
            exit($errCode);
        }
    }
455130
protected byte[] getTransportPayload(AuditEventMessage msg) throws UnsupportedEncodingException
	{
		if (msg == null) {
			return null;
		}
		
		byte[] msgBytes = msg.getSerializedMessage(false);
		if (EventUtils.isEmptyOrNull(msgBytes)) {
			return null;
		}
		
		// Format message with transport-specific headers
		StringBuilder sb = new StringBuilder();
		
		// The breakdown of the ABNF definition of the message are included as comments
		//PRI
		sb.append("<");
		sb.append(TRANSPORT_DEFAULT_PRIORITY);
		sb.append(">");
		//VERSION SP ; the two together since this is a defined value for this header
		sb.append("1 ");
		//TIMESTAMP SP
		sb.append(TimestampUtils.getRFC3881Timestamp(msg.getDateTime()));
		sb.append(" ");
		//HOSTNAME SP
		sb.append(getSystemHostName());
		sb.append(" ");
		//APP-NAME SP; SHOULD identify the device or application that originated the message
		sb.append(TRANSPORT_DEFAULT_APP); 
		sb.append(" ");
		//PROCID SP; a change in this value indicates a discontinuity in the syslog stream
		//       ; often the process name or process ID associated with a syslog system is used
		sb.append(getPROCID());
		sb.append(" ");
		//MSGID SP; SHOULD identify the type of message
		sb.append(TRANSPORT_DEFAULT_MSGID); 
		//sb.append(" "); // added to next string
		//STRUCTURED-DATA
		sb.append(" - "); // this is the nil value, since IHE ATNA does not use it
		//SP MSG
		//sb.append(" "); // added to previous string

		//sb.append("<?xml version=\"1.0\" encoding=\"ASCII\"?>"); // If just ASCII alternative
		/* UTF 8 alternate from Dmytro Rud */
		// BOM for UTF-8
		//sb.append("\u00EF\u00BB\u00BF");
		sb.append("\uFEFF"); // recommended by Jeremy Huiskamp, over the wire result is EF BB EF as I think it should be
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		/* end UTF 8 alternative*/

		// remainder of XML payload
		sb.append(new String(msgBytes, "UTF-8"));

		return sb.toString().trim().getBytes("UTF-8");
	}
310406
public SecurityTokenServiceClient buildClientForRelyingPartyTokenResponses(final SecurityToken securityToken,
                                                                               final WSFederationRegisteredService service) {
        val cxfBus = BusFactory.getDefaultBus();
        val sts = new SecurityTokenServiceClient(cxfBus);
        sts.setAddressingNamespace(StringUtils.defaultIfBlank(service.getAddressingNamespace(), WSFederationConstants.HTTP_WWW_W3_ORG_2005_08_ADDRESSING));
        sts.setWsdlLocation(prepareWsdlLocation(service));
        val namespace = StringUtils.defaultIfBlank(service.getNamespace(), WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512);
        sts.setServiceQName(new QName(namespace, service.getWsdlService()));
        sts.setEndpointQName(new QName(namespace, service.getWsdlEndpoint()));
        sts.setEnableAppliesTo(StringUtils.isNotBlank(service.getAppliesTo()));
        sts.setOnBehalfOf(securityToken.getToken());
        sts.setKeyType(WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
        sts.setTokenType(StringUtils.defaultIfBlank(service.getTokenType(), WSConstants.WSS_SAML2_TOKEN_TYPE));

        if (StringUtils.isNotBlank(service.getPolicyNamespace())) {
            sts.setWspNamespace(service.getPolicyNamespace());
        }

        return sts;
    }
627111
private function checkMsgSignature($msg_signature, $timestamp, $nonce, $encrypt) {
		return \Yii::$app->security->compareString($this->sign([$this->manager->app->token, $timestamp, $nonce, $encrypt]), $msg_signature);
	}
778874
public function getSHA1($token, $timestamp, $nonce, $encrypt_msg)
	{
		//排序
		try {
			$array = array($encrypt_msg, $token, $timestamp, $nonce);
			sort($array, SORT_STRING);
			$str = implode($array);
			return array(ErrorCode::$OK, sha1($str));
		} catch (Exception $e) {
			//print $e . "\n";
			return array(ErrorCode::$ComputeSignatureError, null);
		}
	}
1091640
public function getSignature(RequestInterface $request, $timestamp, $nonce)
    {
        $string = $this->getStringToSign($request, $timestamp, $nonce);
        $key = urlencode($this->config['consumer_secret']) . '&' . urlencode($this->config['token_secret']);

        return base64_encode(call_user_func($this->config['signature_callback'], $string, $key));
    }
583440
public static X509Certificate newCertificateAuthority(X509Metadata metadata, File storeFile, X509Log x509log) {
        try {
            KeyPair caPair = newKeyPair();

            ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPair.getPrivate());

            // clone metadata
            X509Metadata caMetadata = metadata.clone(CA_CN, metadata.password);
            X500Name issuerDN = buildDistinguishedName(caMetadata);

            // Generate self-signed certificate
            X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(
                    issuerDN,
                    BigInteger.valueOf(System.currentTimeMillis()),
                    caMetadata.notBefore,
                    caMetadata.notAfter,
                    issuerDN,
                    caPair.getPublic());

            JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
            caBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(caPair.getPublic()));
            caBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caPair.getPublic()));
            caBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(true));
            caBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));

            JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC);
            X509Certificate cert = converter.getCertificate(caBuilder.build(caSigner));

            // confirm the validity of the CA certificate
            cert.checkValidity(new Date());
            cert.verify(cert.getPublicKey());

            // Delete existing keystore
            if (storeFile.exists()) {
                storeFile.delete();
            }

            // Save private key and certificate to new keystore
            KeyStore store = openKeyStore(storeFile, caMetadata.password);
            store.setKeyEntry(CA_ALIAS, caPair.getPrivate(), caMetadata.password.toCharArray(),
                    new Certificate[]{cert});
            saveKeyStore(storeFile, store, caMetadata.password);

            x509log.log(MessageFormat.format("New CA certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getIssuerDN().getName()));

            // update serial number in metadata object
            caMetadata.serialNumber = cert.getSerialNumber().toString();

            return cert;
        } catch (Throwable t) {
            throw new RuntimeException("Failed to generate Fathom CA certificate!", t);
        }
    }
1202389
public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException {
        try {
            String[] array = new String[]{token, timestamp, nonce, encrypt};
            StringBuffer sb = new StringBuffer();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < 4; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();

            return getSHA1HexString(str);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.ComputeSignatureError);
        }
    }
835058
static PemEncoded toPEM(ByteBufAllocator allocator, boolean useDirect,
            X509Certificate... chain) throws CertificateEncodingException {

        if (chain == null || chain.length == 0) {
            throw new IllegalArgumentException("X.509 certificate chain can't be null or empty");
        }

        // We can take a shortcut if there is only one certificate and
        // it already happens to be a PemEncoded instance. This is the
        // ideal case and reason why all this exists. It allows the user
        // to pass pre-encoded bytes straight into OpenSSL without having
        // to do any of the extra work.
        if (chain.length == 1) {
            X509Certificate first = chain[0];
            if (first instanceof PemEncoded) {
                return ((PemEncoded) first).retain();
            }
        }

        boolean success = false;
        ByteBuf pem = null;
        try {
            for (X509Certificate cert : chain) {

                if (cert == null) {
                    throw new IllegalArgumentException("Null element in chain: " + Arrays.toString(chain));
                }

                if (cert instanceof PemEncoded) {
                    pem = append(allocator, useDirect, (PemEncoded) cert, chain.length, pem);
                } else {
                    pem = append(allocator, useDirect, cert, chain.length, pem);
                }
            }

            PemValue value = new PemValue(pem, false);
            success = true;
            return value;
        } finally {
            // Make sure we never leak the PEM's ByteBuf in the event of an Exception
            if (!success && pem != null) {
                pem.release();
            }
        }
    }
1283223
def security_context(conf):
    
    if not conf:
        return None

    try:
        metadata = conf.metadata
    except AttributeError:
        metadata = None

    try:
        id_attr = conf.id_attr_name
    except AttributeError:
        id_attr = None

    sec_backend = None

    if conf.crypto_backend == 'xmlsec1':
        xmlsec_binary = conf.xmlsec_binary

        if not xmlsec_binary:
            try:
                _path = conf.xmlsec_path
            except AttributeError:
                _path = []
            xmlsec_binary = get_xmlsec_binary(_path)

        # verify that xmlsec is where it's supposed to be
        if not os.path.exists(xmlsec_binary):
            # if not os.access(, os.F_OK):
            err_msg = 'xmlsec binary not found: {binary}'
            err_msg = err_msg.format(binary=xmlsec_binary)
            raise SigverError(err_msg)

        crypto = _get_xmlsec_cryptobackend(xmlsec_binary)

        _file_name = conf.getattr('key_file', '')
        if _file_name:
            try:
                rsa_key = import_rsa_key_from_file(_file_name)
            except Exception as err:
                logger.error('Cannot import key from {file}: {err_msg}'.format(
                    file=_file_name, err_msg=err))
                raise
            else:
                sec_backend = RSACrypto(rsa_key)
    elif conf.crypto_backend == 'XMLSecurity':
        # new and somewhat untested pyXMLSecurity crypto backend.
        crypto = CryptoBackendXMLSecurity()
    else:
        err_msg = 'Unknown crypto_backend {backend}'
        err_msg = err_msg.format(backend=conf.crypto_backend)
        raise SigverError(err_msg)

    enc_key_files = []
    if conf.encryption_keypairs is not None:
        for _encryption_keypair in conf.encryption_keypairs:
            if 'key_file' in _encryption_keypair:
                enc_key_files.append(_encryption_keypair['key_file'])

    return SecurityContext(
            crypto,
            conf.key_file,
            cert_file=conf.cert_file,
            metadata=metadata,
            only_use_keys_in_metadata=conf.only_use_keys_in_metadata,
            cert_handler_extra_class=conf.cert_handler_extra_class,
            generate_cert_info=conf.generate_cert_info,
            tmp_cert_file=conf.tmp_cert_file,
            tmp_key_file=conf.tmp_key_file,
            validate_certificate=conf.validate_certificate,
            enc_key_files=enc_key_files,
            encryption_keypairs=conf.encryption_keypairs,
            sec_backend=sec_backend,
            id_attr=id_attr)