获取服务商凭证

        https://work.weixin.qq.com/api/doc#90001/90143/91200

        :param provider_secret: 服务商的secret，在服务商管理后台可见
        :return: 返回的 JSON 数据包
547205
def get_provider_token(self, provider_secret):
        
        return self._post(
            'service/get_provider_token',
            data={
                'corpid': self._client.corp_id,
                'provider_secret': provider_secret,
            }
        )
43970
static byte[] getSecretBytes(String secret) throws IllegalArgumentException {
        if (secret == null) {
            throw new IllegalArgumentException("The Secret cannot be null");
        }
        return secret.getBytes(StandardCharsets.UTF_8);
    }
1128215
function kandado (secret) {
  // Default Options
  let config = {
    // Token Expiration
    tokenExpiration: '24h',
    // Require Token middleware
    requireToken (req, res, next) {
      res.json({ 'error': 'token_required' })
    },
    // Failed Authentication middleware
    failedAuth (req, res, next) {
      res.json({ 'error': 'token_invalid' })
    }
  }

  return {
    // Config setter
    set (key, value) {
      config[key] = value
    },
    // Config getter (just in-case you need it)
    get (key) {
      return config[key]
    },
    // Token Generator
    generateToken (data, tokenOptions = {}) {
      // Default Token Options
      tokenOptions.expiresIn = config.tokenExpiration

      return new Promise((resolve, reject) => {
        // Encrypt `data` using the given `secret` key
        jwt.sign(data, secret, tokenOptions, (err, token) => {
          if (err) reject(err)
          else resolve(token)
        })
      })
    },
    // Authentication Middleware
    required (req, res, next) {
      // Check GET (req.query) or POST (req.body) data for the 'token' key
      let token = req.query.token || req.body.token || req.headers.authorization

      if (!token) {
        // If no token was passed, proceed to 'requireToken' middleware
        config.requireToken(req, res, next)
      } else {
        // Else, verify 'token' using the given `secret` key
        jwt.verify(token, secret, (err, data) => {
          if (err) {
            // If token is invalid, pass `err` data to `req.authError`...
            req.authError = err
            // then proceed to `failedAuth` middleware
            config.failedAuth(req, res, next)
          } else {
            // Else if token is valid, pass decrypted `data` to `req.authData`...
            req.authData = data
            // then proceed to the next middleware or router callback
            next()
          }
        })
      }
    }
  }
}
74549
protected void checkParameters() {
        // 检查注入的ref是否接口实现类
        Class proxyClass = providerConfig.getProxyClass();
        String key = providerConfig.buildKey();
        T ref = providerConfig.getRef();
        if (!proxyClass.isInstance(ref)) {
            throw ExceptionUtils.buildRuntime("provider.ref",
                ref == null ? "null" : ref.getClass().getName(),
                "This is not an instance of " + providerConfig.getInterfaceId()
                    + " in provider config with key " + key + " !");
        }
        // server 不能为空
        if (CommonUtils.isEmpty(providerConfig.getServer())) {
            throw ExceptionUtils.buildRuntime("server", "NULL", "Value of \"server\" is not specified in provider" +
                " config with key " + key + " !");
        }
        checkMethods(proxyClass);
    }
958833
function jsonRet(req,res) {
    var state = 200;
    var data = {
        code:state,
        message:""
    };

    //错误判断（404）
    if(!req.input) {
        state = 404;
        req.app.yolog.log('error','error 404');
    } else if(req.input.error) {
        state = 500;
        data.message = req.input.message ? req.input.message:'';
        req.app.yolog.log('error','error 500',req.input);
    } else {
        data.data = res.proxyData;
    } 
    req.app.yolog.log('verbose','pjax vo: %j',data,{});
    data.code = state;
    res.status(state).json(data);
}
705751
public function getQRCodeUrl($company, $holder, $secret)
    {
        return 'otpauth://totp/'.urlencode($company.':'.$holder).'?secret='.$secret.'&issuer='.urlencode($company).'';
    }
981191
private static Provider getAndroidSecurityProvider() {
    Provider[] providers = Security.getProviders();
    for (Provider availableProvider : providers) {
      for (String providerClassName : ANDROID_SECURITY_PROVIDERS) {
        if (providerClassName.equals(availableProvider.getClass().getName())) {
          logger.log(Level.FINE, "Found registered provider {0}", providerClassName);
          return availableProvider;
        }
      }
    }
    logger.log(Level.WARNING, "Unable to find Conscrypt");
    return null;
  }
589499
function(secret) {
        var keyIv;
        if (!secret) {
          throw new CError('missing secret').log();
        }
        // secret is a Base64 string
        if(secret.isBase64()){
          try {
            keyIv = forge.util.decode64(secret);
          } catch (e) {
            throw new CError('secret not valid').log();
          }
        } else {
          keyIv = secret;
        }
        return keyIv;
      }
876665
def secret_key_bytes(self):
        ''' 

        '''
        if not hasattr(self, '_secret_key_bytes'):
            key = self.secret_key()
            if key is None:
                self._secret_key_bytes = None
            else:
                self._secret_key_bytes = codecs.encode(key, "utf-8")
        return self._secret_key_bytes
138102
ByteBuffer[] encode(final Supplier<ByteBuffer> supplier, final Consumer<ByteBuffer> consumer, final Cryptor cryptor) {
        final byte opcode = (byte) (this.type.getValue() | 0x80);
        if (this.sendConvert != null) {
            Supplier<ByteBuffer> newsupplier = new Supplier<ByteBuffer>() {

                private ByteBuffer buf = supplier.get();

                @Override
                public ByteBuffer get() {
                    if (buf != null) {
                        ByteBuffer rs = buf;
                        rs.position(6);
                        this.buf = null;
                        return rs;
                    }
                    return supplier.get();
                }
            };
            ByteBuffer[] buffers = this.sendMapconvable ? this.sendConvert.convertMapTo(newsupplier, (Object[]) sendJson) : this.sendConvert.convertTo(newsupplier, sendJson);
            if (cryptor != null) buffers = cryptor.encrypt(buffers, supplier, consumer);
            int len = 0;
            for (ByteBuffer buf : buffers) {
                len += buf.remaining();
            }
            int contentLength = len - 6;
            ByteBuffer firstbuf = buffers[0];
            if (contentLength <= 0x7D) { //125
                firstbuf.put(4, opcode);
                firstbuf.put(5, (byte) contentLength);
                firstbuf.position(4);
            } else if (contentLength <= 0xFFFF) {
                firstbuf.put(2, opcode);
                firstbuf.put(3, (byte) 0x7E); //126
                firstbuf.putChar(4, (char) contentLength);
                firstbuf.position(2);
            } else {
                firstbuf.put(0, opcode);
                firstbuf.put(1, (byte) 0x7F); //127
                firstbuf.putInt(2, contentLength);
            }
            return buffers;
        }

        ByteBuffer buffer = supplier.get();  //确保ByteBuffer的capacity不能小于128
        byte[] content = content();
        if (cryptor != null) {
            ByteBuffer[] ss = new ByteBuffer[]{ByteBuffer.wrap(content)};
            ByteBuffer[] bs = cryptor.encrypt(ss, supplier, consumer);
            if (bs != ss) {
                int r = 0;
                for (ByteBuffer bb : bs) {
                    r += bb.remaining();
                }
                content = new byte[r];
                int index = 0;
                for (ByteBuffer bb : bs) {
                    int re = bb.remaining();
                    bb.get(content, index, re);
                    index += re;
                }
                for (ByteBuffer bb : bs) {
                    consumer.accept(bb);
                }
            }
        }
        final int len = content.length;
        if (len <= 0x7D) { //125
            buffer.put(opcode);
            buffer.put((byte) len);
            buffer.put(content);
            buffer.flip();
            return new ByteBuffer[]{buffer};
        }
        if (len <= 0xFFFF) { // 65535
            buffer.put(opcode);
            buffer.put((byte) 0x7E); //126
            buffer.putChar((char) len);
        } else {
            buffer.put(opcode);
            buffer.put((byte) 0x7F); //127
            buffer.putInt(len);
        }
        int start = buffer.remaining();
        int pend = len - buffer.remaining();
        if (pend <= 0) {
            buffer.put(content);
            buffer.flip();
            return new ByteBuffer[]{buffer};
        }
        buffer.put(content, 0, buffer.remaining());
        buffer.flip();
        final int capacity = buffer.capacity();
        final ByteBuffer[] buffers = new ByteBuffer[(pend / capacity) + 1 + ((pend % capacity) > 0 ? 1 : 0)];
        buffers[0] = buffer;
        for (int i = 1; i < buffers.length; i++) {
            ByteBuffer buf = supplier.get();
            buf.put(content, start, Math.min(pend, capacity));
            buf.flip();
            buffers[i] = buf;
            start += capacity;
            pend -= capacity;
        }
        return buffers;
    }
1249407
function generateSign(api, params, method, secretKey){

	//将method转为大写
	method = method.toUpperCase();
	if(method !== 'GET' && method !== 'POST'){
		throw new Error('method is invalid');
	}

	if(typeof params !== 'object'){
		throw new Error('params is invalid');
	}

	//提取host和path
	var urlParams = url.parse(api);
	var hostPath  = urlParams.host + urlParams.path;

	//对params里的key进行排序
	var arrKey = [];
	for(var key in params){
		arrKey.push(key);
	}
	arrKey.sort();

	//拼接参数字符串
	var strParams = '';
	for(var i=0; i < arrKey.length; i++){
		var value = params[arrKey[i]];
		strParams += arrKey[i] + '=' + value;
	}

	return md5(method + hostPath + strParams + secretKey);
}
570010
def reset_secret(self):
        
        result = self._client.post("{}/reset_secret".format(OAuthClient.api_endpoint), model=self)

        if not 'id' in result:
            raise UnexpectedResponseError('Unexpected response when resetting secret!', json=result)

        self._populate(result)
        return self.secret
139878
def get_api_key(client, username, secret):
    

    # Try to use a client with username/api key
    if len(secret) == 64:
        try:
            client['Account'].getCurrentUser()
            return secret
        except SoftLayer.SoftLayerAPIError as ex:
            if 'invalid api token' not in ex.faultString.lower():
                raise
    else:
        # Try to use a client with username/password
        client.authenticate_with_password(username, secret)

        user_record = client['Account'].getCurrentUser(mask='id, apiAuthenticationKeys')
        api_keys = user_record['apiAuthenticationKeys']
        if len(api_keys) == 0:
            return client['User_Customer'].addApiAuthenticationKey(id=user_record['id'])
        return api_keys[0]['authenticationKey']
872303
def get_provider(self, provider_id, provider_username=''):
        
        magic = self._magic_json(
            action=TouchWorksMagicConstants.ACTION_GET_PROVIDER,
            parameter1=provider_id,
            parameter2=provider_username)
        response = self._http_request(TouchWorksEndPoints.MAGIC_JSON, data=magic)
        result = self._get_results_or_raise_if_magic_invalid(
            magic,
            response,
            TouchWorksMagicConstants.RESULT_GET_PROVIDER)
        return result
564633
def _get_client(self, server):
        
        return Client(
            server=server[0],
            authport=server[1],
            secret=server[2],
            dict=self._get_dictionary(),
        )
216170
def get_jwt_secret():
    
    secret_key = __options__.get("jwt_secret") or config("JWT_SECRET") or config("SECRET_KEY")
    if not secret_key:
        raise exceptions.AuthError("Missing config JWT/SECRET_KEY")
    return secret_key
534511
public static String encryptPin(String accNo, String pin, String encoding,
			PublicKey key) {
		/** 使用公钥对密码加密 **/
		byte[] data = null;
		try {
			data = pin2PinBlockWithCardNO(pin, accNo);
			data = encryptData(key, data);
			return new String(SecureUtil.base64Encode(data), encoding);
		} catch (Exception e) {
			LogUtil.writeErrorLog(e.getMessage(), e);
			return "";
		}
	}