├── .gitignore ├── LICENSE ├── README.md ├── 全民k歌 └── KSong.py ├── 天气推送 └── index.py ├── 天翼云盘签到 ├── bin │ ├── pyrsa-decrypt │ ├── pyrsa-encrypt │ ├── pyrsa-keygen │ ├── pyrsa-priv2pub │ ├── pyrsa-sign │ └── pyrsa-verify ├── ecloud.py ├── pyasn1-0.4.8.dist-info │ ├── INSTALLER │ ├── LICENSE.rst │ ├── METADATA │ ├── RECORD │ ├── WHEEL │ ├── top_level.txt │ └── zip-safe ├── pyasn1 │ ├── __init__.py │ ├── codec │ │ ├── __init__.py │ │ ├── ber │ │ │ ├── __init__.py │ │ │ ├── decoder.py │ │ │ ├── encoder.py │ │ │ └── eoo.py │ │ ├── cer │ │ │ ├── __init__.py │ │ │ ├── decoder.py │ │ │ └── encoder.py │ │ ├── der │ │ │ ├── __init__.py │ │ │ ├── decoder.py │ │ │ └── encoder.py │ │ └── native │ │ │ ├── __init__.py │ │ │ ├── decoder.py │ │ │ └── encoder.py │ ├── compat │ │ ├── __init__.py │ │ ├── binary.py │ │ ├── calling.py │ │ ├── dateandtime.py │ │ ├── integer.py │ │ ├── octets.py │ │ └── string.py │ ├── debug.py │ ├── error.py │ └── type │ │ ├── __init__.py │ │ ├── base.py │ │ ├── char.py │ │ ├── constraint.py │ │ ├── error.py │ │ ├── namedtype.py │ │ ├── namedval.py │ │ ├── opentype.py │ │ ├── tag.py │ │ ├── tagmap.py │ │ ├── univ.py │ │ └── useful.py ├── rsa-4.6.dist-info │ ├── INSTALLER │ ├── LICENSE │ ├── METADATA │ ├── RECORD │ ├── WHEEL │ ├── entry_points.txt │ └── top_level.txt └── rsa │ ├── __init__.py │ ├── _compat.py │ ├── _version133.py │ ├── _version200.py │ ├── asn1.py │ ├── bigfile.py │ ├── cli.py │ ├── common.py │ ├── core.py │ ├── key.py │ ├── parallel.py │ ├── pem.py │ ├── pkcs1.py │ ├── pkcs1_v2.py │ ├── prime.py │ ├── randnum.py │ ├── transform.py │ ├── util.py │ └── varblock.py ├── 百度贴吧签到 ├── config.json └── index.py ├── 网易云音乐 ├── account.json ├── index.py └── init.config └── 腾讯视频签到 ├── config.json ├── demo.json ├── index.py └── template.yaml /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Serverless-Python 2 | 3 | 4 | ## :star2:全民K歌签到 5 | * 功能简介:签到领取包含邮局120朵,6项签到,每日抽奖及签到7日抽奖,把签到信息推送到微信 6 | 7 | #### 安装教程 8 | 9 | #### 效果显示 10 | 11 | 12 | ## :sunny:天气推送 13 | * 功能简介:自动爬取天气信息,并推送到QQ 14 | 15 | #### 安装教程 16 | 17 | #### 效果显示 18 | 19 | ## :crystal_ball:天翼云盘签到 20 | * 功能简介:天翼云盘每日签到一次,抽奖2次,添加SERVER酱签到的微信推送 21 | 22 | #### 安装教程 23 | 24 | #### 效果显示 25 | 26 | ## :page_with_curl:百度贴吧签到 27 | * 功能简介:百度贴吧签到并把签到信息推送到微信 28 | 29 | #### 安装教程 30 | 31 | #### 效果显示 32 | 33 | 34 | ## :dart:网易云音乐 35 | * 功能简介:调用API完成每日300首的听歌量,并获取听歌量信息推送到微信 36 | 37 | #### 安装教程 38 | 39 | #### 效果显示 40 | 41 | 42 | ## :crown:腾讯视频签到 43 | * 功能简介:完成每日两次签到获取积分升级 44 | 45 | #### 安装教程 46 | 47 | #### 效果显示 48 | 49 | 50 | -------------------------------------------------------------------------------- /全民k歌/KSong.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | import requests 3 | ''' 4 | -包含邮局120朵,6项签到,每日抽奖及签到7日抽奖 5 | -sckey- Server酱SCKEY 6 | -Cookie- Cookie 7 | ''' 8 | 9 | sckey = '' 10 | Cookie = '' 11 | 12 | 13 | uid = Cookie.split("; ") 14 | t_uUid = '' 15 | for i in uid: 16 | if i.find('uid=') >= 0: 17 | t_uUid = i.split('=')[1] 18 | Url_a = 'https://node.kg.qq.com/webapp/proxy?ns=proto_profile&cmd=profile.getProfile&mapExt=JTdCJTIyZmlsZSUyMiUzQSUyMnByb2ZpbGVfd2ViYXBwSmNlJTIyJTJDJTIyY21kTmFtZSUyMiUzQSUyMlByb2ZpbGVHZXQlMjIlMkMlMjJhcHBpZCUyMiUzQTEwMDA2MjYlMkMlMjJkY2FwaSUyMiUzQSU3QiUyMmludGVyZmFjZUlkJTIyJTNBMjA1MzU5NTk3JTdEJTJDJTIybDVhcGklMjIlM0ElN0IlMjJtb2RpZCUyMiUzQTI5NDAxNyUyQyUyMmNtZCUyMiUzQTI2MjE0NCU3RCUyQyUyMmlwJTIyJTNBJTIyMTAwLjExMy4xNjIuMTc4JTIyJTJDJTIycG9ydCUyMiUzQSUyMjEyNDA2JTIyJTdE&t_uUid=' + t_uUid 19 | Url_b = 'https://node.kg.qq.com/webapp/proxy?ns=KG_TASK&cmd=task.getLottery&ns_inbuf=&mapExt=JTdCJTIyZmlsZSUyMiUzQSUyMnRhc2tKY2UlMjIlMkMlMjJjbWROYW1lJTIyJTNBJTIyTG90dGVyeVJlcSUyMiUyQyUyMnduc0NvbmZpZyUyMiUzQSU3QiUyMmFwcGlkJTIyJTNBMTAwMDU1NyU3RCUyQyUyMmw1YXBpJTIyJTNBJTdCJTIybW9kaWQlMjIlM0E1MDM5MzclMkMlMjJjbWQlMjIlM0E1ODk4MjQlN0QlN0Q%3D&t_uid=' + t_uUid + '&t_iShowEntry=1&t_type=' 20 | t_type = ['1','2'] 21 | Url_e = 'https://node.kg.qq.com/webapp/proxy?ns=KG_TASK&cmd=task.getLottery&mapExt=JTdCJTIyZmlsZSUyMiUzQSUyMnRhc2tKY2UlMjIlMkMlMjJjbWROYW1lJTIyJTNBJTIyTG90dGVyeVJlcSUyMiUyQyUyMmw1YXBpJTIyJTNBJTdCJTIybW9kaWQlMjIlM0E1MDM5MzclMkMlMjJjbWQlMjIlM0E1ODk4MjQlN0QlMkMlMjJsNWFwaV9leHAxJTIyJTNBJTdCJTIybW9kaWQlMjIlM0E4MTcwODklMkMlMjJjbWQlMjIlM0EzODAxMDg4JTdEJTdE&t_uid=' + t_uUid + '&t_type=103' 22 | 23 | Url_c = 'https://node.kg.qq.com/webapp/proxy?ns=KG_TASK&cmd=task.signinGetAward&mapExt=JTdCJTIyZmlsZSUyMiUzQSUyMnRhc2tKY2UlMjIlMkMlMjJjbWROYW1lJTIyJTNBJTIyR2V0U2lnbkluQXdhcmRSZXElMjIlMkMlMjJ3bnNDb25maWclMjIlM0ElN0IlMjJhcHBpZCUyMiUzQTEwMDA2MjYlN0QlMkMlMjJsNWFwaSUyMiUzQSU3QiUyMm1vZGlkJTIyJTNBNTAzOTM3JTJDJTIyY21kJTIyJTNBNTg5ODI0JTdEJTdE&t_uid=' + t_uUid + '&t_iShowEntry=' 24 | t_iShowEntry =['1','2','4','16','128','512'] 25 | Url_d = 'https://node.kg.qq.com/webapp/proxy?ns=KG_TASK&cmd=task.getLottery&mapExt=JTdCJTIyZmlsZSUyMiUzQSUyMnRhc2tKY2UlMjIlMkMlMjJjbWROYW1lJTIyJTNBJTIyTG90dGVyeVJlcSUyMiUyQyUyMnduc0NvbmZpZyUyMiUzQSU3QiUyMmFwcGlkJTIyJTNBMTAwMDU1NyU3RCUyQyUyMmw1YXBpJTIyJTNBJTdCJTIybW9kaWQlMjIlM0E1MDM5MzclMkMlMjJjbWQlMjIlM0E1ODk4MjQlN0QlN0Q&t_uid=' + t_uUid + '&t_iShowEntry=4&t_type=104' 26 | Url_1 = 'https://node.kg.qq.com/webapp/proxy?ns=proto_music_station&cmd=message.batch_get_music_cards&mapExt=JTdCJTIyY21kTmFtZSUyMiUzQSUyMkdldEJhdGNoTXVzaWNDYXJkc1JlcSUyMiUyQyUyMmZpbGUlMjIlM0ElMjJwcm90b19tdXNpY19zdGF0aW9uSmNlJTIyJTJDJTIyd25zRGlzcGF0Y2hlciUyMiUzQXRydWUlN0Q&t_uUid=' + t_uUid + '&g_tk_openkey=' 27 | Url_2 = 'https://node.kg.qq.com/webapp/proxy?t_stReward%3Aobject=%7B%22uInteractiveType%22%3A1%2C%22uRewardType%22%3A0%2C%22uFlowerNum%22%3A15%7D&ns=proto_music_station&cmd=message.get_reward&mapExt=JTdCJTIyY21kTmFtZSUyMiUzQSUyMkdldFJld2FyZFJlcSUyMiUyQyUyMmZpbGUlMjIlM0ElMjJwcm90b19tdXNpY19zdGF0aW9uSmNlJTIyJTJDJTIyd25zRGlzcGF0Y2hlciUyMiUzQXRydWUlN0Q&t_uUid=' + t_uUid + '&t_strUgcId=' 28 | Url_3 = 'https://node.kg.qq.com/webapp/proxy?t_stReward%3Aobject=%7B%22uInteractiveType%22%3A0%2C%22uRewardType%22%3A0%2C%22uFlowerNum%22%3A10%7D&ns=proto_music_station&cmd=message.get_reward&mapExt=JTdCJTIyY21kTmFtZSUyMiUzQSUyMkdldFJld2FyZFJlcSUyMiUyQyUyMmZpbGUlMjIlM0ElMjJwcm90b19tdXNpY19zdGF0aW9uSmNlJTIyJTJDJTIyd25zRGlzcGF0Y2hlciUyMiUzQXRydWUlN0Q&t_uUid=' + t_uUid + '&t_strUgcId=' 29 | 30 | def run(): 31 | try: 32 | res_1 = requests.get(Url_a, headers={'Cookie': Cookie}) 33 | num_a = res_1.json()['data']['profile.getProfile']['uFlowerNum'] 34 | for index, T_iShowEntry in enumerate(t_iShowEntry): 35 | res_b = requests.get(Url_c + T_iShowEntry, headers={'Cookie': Cookie}) 36 | for index, T_type in enumerate(t_type): 37 | res_a = requests.get(Url_b + T_type, headers={'Cookie': Cookie}) 38 | for g_tk_openkey in range(16): 39 | res_2 = requests.get(Url_1 + str(g_tk_openkey), headers={'Cookie': Cookie}) 40 | vctMusicCards = res_2.json()['data']['message.batch_get_music_cards']['vctMusicCards'] 41 | List = sorted(vctMusicCards,key=lambda x: x['stReward']['uFlowerNum'],reverse=True)[0] 42 | strUgcId = List['strUgcId'] 43 | strKey = List['strKey'] 44 | Url = strUgcId + '&t_strKey=' + strKey 45 | if List['stReward']['uFlowerNum'] > 10: 46 | res_3 = requests.get(Url_2 + Url, headers={'Cookie': Cookie}) 47 | else: 48 | if List['stReward']['uFlowerNum'] > 1: 49 | res_3 = requests.get(Url_3 + Url, headers={'Cookie': Cookie}) 50 | res_f = requests.get(Url_d, headers={'Cookie': Cookie}) 51 | res_d = requests.get(Url_e, headers={'Cookie': Cookie}) 52 | res_4 = requests.get(Url_a, headers={'Cookie': Cookie}) 53 | num_b = res_4.json()['data']['profile.getProfile']['uFlowerNum'] 54 | num_c = int(num_b)-int(num_a) 55 | if num_c == 0: 56 | num = '请不要重复领取哦.....当前账户为' + str(num_b) + '朵鲜花!' 57 | else: 58 | num = '本次成功领取' + str(num_c) + '朵鲜花!' 59 | except: 60 | num = 'Cookie效验失败' 61 | requests.get('https://sc.ftqq.com/' + sckey + '.send?text=全民K歌签到通知&desp=' + num) 62 | print(num) 63 | 64 | def main_handler(event, context): 65 | run() -------------------------------------------------------------------------------- /天气推送/index.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | #本项目不建议使用server酱,因为不够直观 3 | import requests, json 4 | import time 5 | 6 | spkey = '' #CoolPush酷推 7 | def get_iciba_everyday(): 8 | icbapi = 'http://open.iciba.com/dsapi/' 9 | eed = requests.get(icbapi) 10 | bee = eed.json() #返回的数据 11 | english = eed.json()['content'] 12 | zh_CN = eed.json()['note'] 13 | str = '\n【奇怪的知识】\n' + english + '\n' + zh_CN 14 | return str 15 | 16 | # print(get_iciba_everyday()) 17 | 18 | def main(*args): 19 | api = 'http://t.weather.itboy.net/api/weather/city/' #API地址,必须配合城市代码使用 20 | city_code = '101260406' #进入https://where.heweather.com/index.html查询你的城市代码 21 | tqurl = api + city_code 22 | response = requests.get(tqurl) 23 | d = response.json() #将数据以json形式返回,这个d就是返回的json数据 24 | print(d) 25 | 26 | if(d['status'] == 200): #当返回状态码为200,输出天气状况 27 | print("城市:",d["cityInfo"]["parent"], d["cityInfo"]["city"]) 28 | print("更新时间:",d["time"]) 29 | print("日期:",d["data"]["forecast"][0]["ymd"]) 30 | print("星期:",d["data"]["forecast"][0]["week"]) 31 | print("天气:",d["data"]["forecast"][0]["type"]) 32 | print("温度:",d["data"]["forecast"][0]["high"],d["data"]["forecast"][0]["low"]) 33 | print("湿度:",d["data"]["shidu"]) 34 | print("PM25:",d["data"]["pm25"]) 35 | print("PM10:",d["data"]["pm10"]) 36 | print("空气质量:",d["data"]["quality"]) 37 | print("风力风向:",d["data"]["forecast"][0]["fx"],d["data"]["forecast"][0]["fl"]) 38 | print("感冒指数:",d["data"]["ganmao"]) 39 | print("温馨提示:",d["data"]["forecast"][0]["notice"],"。") 40 | 41 | cpurl = 'https://push.xuthus.cc/send/'+spkey #自己改发送方式,我专门创建了个群来收消息,所以我用的group 42 | tdwt = '【今日天气】\n城市:'+d['cityInfo']['parent']+' '+d['cityInfo']['city']+'\n日期:'+d["data"]["forecast"][0]["ymd"]+'\n星期:'+d["data"]["forecast"][0]["week"]+'\n天气:'+d["data"]["forecast"][0]["type"]+'\n温度:'+d["data"]["forecast"][0]["high"]+' '+d["data"]["forecast"][0]["low"]+'\n湿度:'+d["data"]["shidu"]+'\n空气质量:'+d["data"]["quality"]+'\n风力风向:'+d["data"]["forecast"][0]["fx"]+' '+d["data"]["forecast"][0]["fl"]+'\n温馨提示:'+d["data"]["forecast"][0]["notice"]+'。\n[Time:'+d["time"]+']\n' #天气提示内容,基本上该有的都做好了,如果要添加信息可以看上面的print,我感觉有用的我都弄进来了。 43 | requests.post(cpurl,tdwt.encode('utf-8')) #把天气数据转换成UTF-8格式,不然要报错。 44 | else: 45 | error = '【出现错误】\n  今日天气推送错误,请检查服务状态!' 46 | requests.post(cpurl,error.encode('utf-8')) 47 | 48 | def main_handler(event, context): 49 | return main() 50 | 51 | if __name__ == '__main__': 52 | main() -------------------------------------------------------------------------------- /天翼云盘签到/bin/pyrsa-decrypt: -------------------------------------------------------------------------------- 1 | #!/var/lang/python3/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import re 4 | import sys 5 | from rsa.cli import decrypt 6 | if __name__ == '__main__': 7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) 8 | sys.exit(decrypt()) 9 | -------------------------------------------------------------------------------- /天翼云盘签到/bin/pyrsa-encrypt: -------------------------------------------------------------------------------- 1 | #!/var/lang/python3/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import re 4 | import sys 5 | from rsa.cli import encrypt 6 | if __name__ == '__main__': 7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) 8 | sys.exit(encrypt()) 9 | -------------------------------------------------------------------------------- /天翼云盘签到/bin/pyrsa-keygen: -------------------------------------------------------------------------------- 1 | #!/var/lang/python3/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import re 4 | import sys 5 | from rsa.cli import keygen 6 | if __name__ == '__main__': 7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) 8 | sys.exit(keygen()) 9 | -------------------------------------------------------------------------------- /天翼云盘签到/bin/pyrsa-priv2pub: -------------------------------------------------------------------------------- 1 | #!/var/lang/python3/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import re 4 | import sys 5 | from rsa.util import private_to_public 6 | if __name__ == '__main__': 7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) 8 | sys.exit(private_to_public()) 9 | -------------------------------------------------------------------------------- /天翼云盘签到/bin/pyrsa-sign: -------------------------------------------------------------------------------- 1 | #!/var/lang/python3/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import re 4 | import sys 5 | from rsa.cli import sign 6 | if __name__ == '__main__': 7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) 8 | sys.exit(sign()) 9 | -------------------------------------------------------------------------------- /天翼云盘签到/bin/pyrsa-verify: -------------------------------------------------------------------------------- 1 | #!/var/lang/python3/bin/python3 2 | # -*- coding: utf-8 -*- 3 | import re 4 | import sys 5 | from rsa.cli import verify 6 | if __name__ == '__main__': 7 | sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) 8 | sys.exit(verify()) 9 | -------------------------------------------------------------------------------- /天翼云盘签到/ecloud.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/env python 2 | # coding=utf-8 3 | import sys, requests, time, re, rsa, json, base64, time, pytz, datetime 4 | from urllib import parse 5 | from io import StringIO 6 | 7 | s = requests.Session() 8 | 9 | # Python版本 3.6,Forked from "https://github.com/mengshouer/Cloud189Checkin" 10 | # 请依次修改 13、14、15行中的需要修改的部分内容 11 | # 天翼云盘每日签到一次,抽奖2次,添加SERVER酱签到的微信推送 12 | 13 | username = "" 14 | password = "" 15 | SCKEY = "" 16 | #Server酱推送提醒,需要填写sckey,官网:https://sc.ftqq.com/3.version 17 | 18 | #SERVER酱微信推送url 19 | scurl = f"https://sc.ftqq.com/{SCKEY}.send" 20 | 21 | # 初始化日志 22 | sio = StringIO('天翼云盘签到日志\n\n') 23 | sio.seek(0, 2) # 将读写位置移动到结尾 24 | tz = pytz.timezone('Asia/Shanghai') 25 | nowtime = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") 26 | sio.write("--------------------------"+nowtime+"----------------------------\n\n") 27 | 28 | 29 | def main(arg1,arg2): 30 | if(username == "" or password == ""): 31 | sio.write('签到失败:用户名或密码为空,请设置\n\n') 32 | desp = sio.getvalue() 33 | pushWechat(desp,nowtime) 34 | return None 35 | # username = input("账号:") 36 | # password = input("密码:") 37 | msg = login(username, password) 38 | if(msg == "error"): 39 | desp = sio.getvalue() 40 | pushWechat(desp,nowtime) 41 | return None 42 | else: 43 | pass 44 | rand = str(round(time.time()*1000)) 45 | surl = f'https://api.cloud.189.cn/mkt/userSign.action?rand={rand}&clientType=TELEANDROID&version=8.6.3&model=SM-G930K' 46 | url = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN&activityId=ACT_SIGNIN' 47 | url2 = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN_PHOTOS&activityId=ACT_SIGNIN' 48 | headers = { 49 | 'User-Agent':'Mozilla/5.0 (Linux; Android 5.1.1; SM-G930K Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.136 Mobile Safari/537.36 Ecloud/8.6.3 Android/22 clientId/355325117317828 clientModel/SM-G930K imsi/460071114317824 clientChannelId/qq proVersion/1.0.6', 50 | "Referer" : "https://m.cloud.189.cn/zhuanti/2016/sign/index.jsp?albumBackupOpened=1", 51 | "Host" : "m.cloud.189.cn", 52 | "Accept-Encoding" : "gzip, deflate", 53 | } 54 | #签到 55 | response = s.get(surl,headers=headers) 56 | netdiskBonus = response.json()['netdiskBonus'] 57 | if(response.json()['isSign'] == "false"): 58 | sio.write(f"签到提示:未签到,签到获得{netdiskBonus}M空间\n\n") 59 | else: 60 | sio.write(f"签到提示:已经签到过了,签到获得{netdiskBonus}M空间\n\n") 61 | headers = { 62 | 'User-Agent':'Mozilla/5.0 (Linux; Android 5.1.1; SM-G930K Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.136 Mobile Safari/537.36 Ecloud/8.6.3 Android/22 clientId/355325117317828 clientModel/SM-G930K imsi/460071114317824 clientChannelId/qq proVersion/1.0.6', 63 | "Referer" : "https://m.cloud.189.cn/zhuanti/2016/sign/index.jsp?albumBackupOpened=1", 64 | "Host" : "m.cloud.189.cn", 65 | "Accept-Encoding" : "gzip, deflate", 66 | } 67 | #第一次抽奖 68 | response = s.get(url,headers=headers) 69 | if ("errorCode" in response.text): 70 | if(response.json()['errorCode'] == "User_Not_Chance"): 71 | sio.write("第一次抽奖:抽奖次数不足\n\n") 72 | else: 73 | sio.write("第一次抽奖失败\n\n") 74 | sio.write(response.text) 75 | sio.write("\n\n") 76 | else: 77 | description = response.json()['description'] 78 | sio.write(f"第一次抽奖:抽奖获得{description}\n\n") 79 | #第二次抽奖 80 | response = s.get(url2,headers=headers) 81 | if ("errorCode" in response.text): 82 | if(response.json()['errorCode'] == "User_Not_Chance"): 83 | sio.write("第二次抽奖:抽奖次数不足\n\n") 84 | else: 85 | sio.write("第二次抽奖失败\n\n") 86 | sio.write(response.text) 87 | sio.write("\n\n") 88 | else: 89 | description = response.json()['description'] 90 | sio.write(f"第二次抽奖:抽奖获得{description}\n\n") 91 | desp = sio.getvalue() 92 | pushWechat(desp,nowtime) 93 | return desp 94 | 95 | BI_RM = list("0123456789abcdefghijklmnopqrstuvwxyz") 96 | def int2char(a): 97 | return BI_RM[a] 98 | 99 | b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" 100 | def b64tohex(a): 101 | d = "" 102 | e = 0 103 | c = 0 104 | for i in range(len(a)): 105 | if list(a)[i] != "=": 106 | v = b64map.index(list(a)[i]) 107 | if 0 == e: 108 | e = 1 109 | d += int2char(v >> 2) 110 | c = 3 & v 111 | elif 1 == e: 112 | e = 2 113 | d += int2char(c << 2 | v >> 4) 114 | c = 15 & v 115 | elif 2 == e: 116 | e = 3 117 | d += int2char(c) 118 | d += int2char(v >> 2) 119 | c = 3 & v 120 | else: 121 | e = 0 122 | d += int2char(c << 2 | v >> 4) 123 | d += int2char(15 & v) 124 | if e == 1: 125 | d += int2char(c << 2) 126 | return d 127 | 128 | 129 | def rsa_encode(j_rsakey, string): 130 | rsa_key = f"-----BEGIN PUBLIC KEY-----\n{j_rsakey}\n-----END PUBLIC KEY-----" 131 | pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(rsa_key.encode()) 132 | result = b64tohex((base64.b64encode(rsa.encrypt(f'{string}'.encode(), pubkey))).decode()) 133 | return result 134 | 135 | def calculate_md5_sign(params): 136 | return hashlib.md5('&'.join(sorted(params.split('&'))).encode('utf-8')).hexdigest() 137 | 138 | def login(username, password): 139 | url = "https://cloud.189.cn/udb/udb_login.jsp?pageId=1&redirectURL=/main.action" 140 | r = s.get(url) 141 | captchaToken = re.findall(r"captchaToken' value='(.+?)'", r.text)[0] 142 | lt = re.findall(r'lt = "(.+?)"', r.text)[0] 143 | returnUrl = re.findall(r"returnUrl = '(.+?)'", r.text)[0] 144 | paramId = re.findall(r'paramId = "(.+?)"', r.text)[0] 145 | j_rsakey = re.findall(r'j_rsaKey" value="(\S+)"', r.text, re.M)[0] 146 | s.headers.update({"lt": lt}) 147 | 148 | username = rsa_encode(j_rsakey, username) 149 | password = rsa_encode(j_rsakey, password) 150 | url = "https://open.e.189.cn/api/logbox/oauth2/loginSubmit.do" 151 | headers = { 152 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/76.0', 153 | 'Referer': 'https://open.e.189.cn/', 154 | } 155 | data = { 156 | "appKey": "cloud", 157 | "accountType": '01', 158 | "userName": f"{{RSA}}{username}", 159 | "password": f"{{RSA}}{password}", 160 | "validateCode": "", 161 | "captchaToken": captchaToken, 162 | "returnUrl": returnUrl, 163 | "mailSuffix": "@189.cn", 164 | "paramId": paramId 165 | } 166 | r = s.post(url, data=data, headers=headers, timeout=5) 167 | if(r.json()['result'] == 0): 168 | sio.write("登录提示:") 169 | sio.write(r.json()['msg']) 170 | sio.write("\n\n") 171 | else: 172 | if(SCKEY == ""): 173 | sio.write("登录提示:") 174 | sio.write(r.json()['msg']) 175 | sio.write("\n\n") 176 | else: 177 | msg = r.json()['msg'] 178 | sio.write("签到失败:登录出错\n\n") 179 | sio.write("错误提示:\n\n") 180 | sio.write(msg) 181 | sio.write("\n\n") 182 | return "error" 183 | redirect_url = r.json()['toUrl'] 184 | r = s.get(redirect_url) 185 | return s 186 | 187 | # 微信推送 188 | def pushWechat(desp,nowtime): 189 | if '失败' in desp : 190 | params = { 191 | 'text': '天翼云盘签到失败提醒' + nowtime, 192 | 'desp': desp 193 | } 194 | else: 195 | params = { 196 | 'text': '天翼云盘签到提醒' + nowtime, 197 | 'desp': desp 198 | } 199 | requests.post(scurl,params=params) 200 | 201 | if __name__ == "__main__": 202 | arg1 = 0 203 | arg2 = 0 204 | main(arg1,arg2) -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1-0.4.8.dist-info/INSTALLER: -------------------------------------------------------------------------------- 1 | pip 2 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1-0.4.8.dist-info/LICENSE.rst: -------------------------------------------------------------------------------- 1 | Copyright (c) 2005-2019, Ilya Etingof 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 | POSSIBILITY OF SUCH DAMAGE. 25 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1-0.4.8.dist-info/METADATA: -------------------------------------------------------------------------------- 1 | Metadata-Version: 2.1 2 | Name: pyasn1 3 | Version: 0.4.8 4 | Summary: ASN.1 types and codecs 5 | Home-page: https://github.com/etingof/pyasn1 6 | Author: Ilya Etingof 7 | Author-email: etingof@gmail.com 8 | Maintainer: Ilya Etingof 9 | License: BSD 10 | Platform: any 11 | Classifier: Development Status :: 5 - Production/Stable 12 | Classifier: Environment :: Console 13 | Classifier: Intended Audience :: Developers 14 | Classifier: Intended Audience :: Education 15 | Classifier: Intended Audience :: Information Technology 16 | Classifier: Intended Audience :: System Administrators 17 | Classifier: Intended Audience :: Telecommunications Industry 18 | Classifier: License :: OSI Approved :: BSD License 19 | Classifier: Natural Language :: English 20 | Classifier: Operating System :: OS Independent 21 | Classifier: Programming Language :: Python :: 2 22 | Classifier: Programming Language :: Python :: 2.4 23 | Classifier: Programming Language :: Python :: 2.5 24 | Classifier: Programming Language :: Python :: 2.6 25 | Classifier: Programming Language :: Python :: 2.7 26 | Classifier: Programming Language :: Python :: 3 27 | Classifier: Programming Language :: Python :: 3.2 28 | Classifier: Programming Language :: Python :: 3.3 29 | Classifier: Programming Language :: Python :: 3.4 30 | Classifier: Programming Language :: Python :: 3.5 31 | Classifier: Programming Language :: Python :: 3.6 32 | Classifier: Programming Language :: Python :: 3.7 33 | Classifier: Topic :: Communications 34 | Classifier: Topic :: Software Development :: Libraries :: Python Modules 35 | 36 | Pure-Python implementation of ASN.1 types and DER/BER/CER codecs (X.208) 37 | 38 | 39 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1-0.4.8.dist-info/RECORD: -------------------------------------------------------------------------------- 1 | pyasn1-0.4.8.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 2 | pyasn1-0.4.8.dist-info/LICENSE.rst,sha256=IsXMaSKrXWn7oy2MXuTN0UmBUIy1OvwOvYVZOEf9laU,1334 3 | pyasn1-0.4.8.dist-info/METADATA,sha256=Mx_DbLo2GA_t9nOIsqu-18vjHdTjMR1LtUzdcfLzE0Y,1521 4 | pyasn1-0.4.8.dist-info/RECORD,, 5 | pyasn1-0.4.8.dist-info/WHEEL,sha256=8zNYZbwQSXoB9IfXOjPfeNwvAsALAjffgk27FqvCWbo,110 6 | pyasn1-0.4.8.dist-info/top_level.txt,sha256=dnNEQt3nIDIO5mSCCOB5obQHrjDOUsRycdBujc2vrWE,7 7 | pyasn1-0.4.8.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 8 | pyasn1/__init__.py,sha256=1Rn8wrJioqfDz7ORFwMehoT15xHOVeiiQD5pZW37D8s,175 9 | pyasn1/__pycache__/__init__.cpython-36.pyc,, 10 | pyasn1/__pycache__/debug.cpython-36.pyc,, 11 | pyasn1/__pycache__/error.cpython-36.pyc,, 12 | pyasn1/codec/__init__.py,sha256=EEDlJYS172EH39GUidN_8FbkNcWY9OVV8e30AV58pn0,59 13 | pyasn1/codec/__pycache__/__init__.cpython-36.pyc,, 14 | pyasn1/codec/ber/__init__.py,sha256=EEDlJYS172EH39GUidN_8FbkNcWY9OVV8e30AV58pn0,59 15 | pyasn1/codec/ber/__pycache__/__init__.cpython-36.pyc,, 16 | pyasn1/codec/ber/__pycache__/decoder.cpython-36.pyc,, 17 | pyasn1/codec/ber/__pycache__/encoder.cpython-36.pyc,, 18 | pyasn1/codec/ber/__pycache__/eoo.cpython-36.pyc,, 19 | pyasn1/codec/ber/decoder.py,sha256=7-WINr38zVEa3KUkmshh8FjK6QnFaA8Y7j7XaTgYfRk,59708 20 | pyasn1/codec/ber/encoder.py,sha256=xHl01PCIAiHZXev4x01sjbCgAUKcsTT6SzaLI3nt-9E,27741 21 | pyasn1/codec/ber/eoo.py,sha256=eZ6lEyHdayMcMmNqtceDIyzf7u5lOeZoRK-WEUxVThI,626 22 | pyasn1/codec/cer/__init__.py,sha256=EEDlJYS172EH39GUidN_8FbkNcWY9OVV8e30AV58pn0,59 23 | pyasn1/codec/cer/__pycache__/__init__.cpython-36.pyc,, 24 | pyasn1/codec/cer/__pycache__/decoder.cpython-36.pyc,, 25 | pyasn1/codec/cer/__pycache__/encoder.cpython-36.pyc,, 26 | pyasn1/codec/cer/decoder.py,sha256=ZYBqtDGNiYmKDpKDvioMDf-TYVWoJeZY3I8TEAKuk5s,3745 27 | pyasn1/codec/cer/encoder.py,sha256=PGtzcIelIHj5d5Yqc5FATMEIWCJybQYFlCaK1gy-NIA,9409 28 | pyasn1/codec/der/__init__.py,sha256=EEDlJYS172EH39GUidN_8FbkNcWY9OVV8e30AV58pn0,59 29 | pyasn1/codec/der/__pycache__/__init__.cpython-36.pyc,, 30 | pyasn1/codec/der/__pycache__/decoder.cpython-36.pyc,, 31 | pyasn1/codec/der/__pycache__/encoder.cpython-36.pyc,, 32 | pyasn1/codec/der/decoder.py,sha256=kinXcogMDPGlR3f7hmAxRv2YbQyeP-UhuKM0r8gkbeA,2722 33 | pyasn1/codec/der/encoder.py,sha256=ZfRRxSCefQyLg0DLNb4zllaYf5_AWGIv3SPzB83Ln2I,3073 34 | pyasn1/codec/native/__init__.py,sha256=EEDlJYS172EH39GUidN_8FbkNcWY9OVV8e30AV58pn0,59 35 | pyasn1/codec/native/__pycache__/__init__.cpython-36.pyc,, 36 | pyasn1/codec/native/__pycache__/decoder.cpython-36.pyc,, 37 | pyasn1/codec/native/__pycache__/encoder.cpython-36.pyc,, 38 | pyasn1/codec/native/decoder.py,sha256=4Q29tdKyytK3Oz-m94MSWxxPi_GhcBKvUfvPNKQcL0Y,7671 39 | pyasn1/codec/native/encoder.py,sha256=0eMLWR49dwMA1X4si0XswR1kX1aDAWyCeUNTpEbChag,8002 40 | pyasn1/compat/__init__.py,sha256=EEDlJYS172EH39GUidN_8FbkNcWY9OVV8e30AV58pn0,59 41 | pyasn1/compat/__pycache__/__init__.cpython-36.pyc,, 42 | pyasn1/compat/__pycache__/binary.cpython-36.pyc,, 43 | pyasn1/compat/__pycache__/calling.cpython-36.pyc,, 44 | pyasn1/compat/__pycache__/dateandtime.cpython-36.pyc,, 45 | pyasn1/compat/__pycache__/integer.cpython-36.pyc,, 46 | pyasn1/compat/__pycache__/octets.cpython-36.pyc,, 47 | pyasn1/compat/__pycache__/string.cpython-36.pyc,, 48 | pyasn1/compat/binary.py,sha256=mgWqHmr_SMEdB2WVVr6jyYMnodSbPP6IByE5qKccWLM,698 49 | pyasn1/compat/calling.py,sha256=uTk3nJtGrElqJi8t34SoO8-eWFBG0gwNhXrlo1YmFEE,379 50 | pyasn1/compat/dateandtime.py,sha256=zHvXXBp4t3XJ6teg_tz6qgNDevzd93qnrLoEbNxZQ_E,482 51 | pyasn1/compat/integer.py,sha256=k6tqyxXMC0zJoU-Rz4oUPPoUpTmWXE6Prnzu0tkmmks,2988 52 | pyasn1/compat/octets.py,sha256=ICe-DVLBIOHmNSz-sp3ioMh--smodJ4VW3Ju0ogJMWA,1359 53 | pyasn1/compat/string.py,sha256=exqXJmPM6vYj4MjzsjciQdpUcJprRdgrLma8I4UcYHA,505 54 | pyasn1/debug.py,sha256=HWGbLlEPLoCNyHqBd1Vd_KK91TppEn3CA4YgUxktT2k,3726 55 | pyasn1/error.py,sha256=DIn2FWY3ACYNbk_42b3ny2bevkehpK2lOqfAsfdkvBE,2257 56 | pyasn1/type/__init__.py,sha256=EEDlJYS172EH39GUidN_8FbkNcWY9OVV8e30AV58pn0,59 57 | pyasn1/type/__pycache__/__init__.cpython-36.pyc,, 58 | pyasn1/type/__pycache__/base.cpython-36.pyc,, 59 | pyasn1/type/__pycache__/char.cpython-36.pyc,, 60 | pyasn1/type/__pycache__/constraint.cpython-36.pyc,, 61 | pyasn1/type/__pycache__/error.cpython-36.pyc,, 62 | pyasn1/type/__pycache__/namedtype.cpython-36.pyc,, 63 | pyasn1/type/__pycache__/namedval.cpython-36.pyc,, 64 | pyasn1/type/__pycache__/opentype.cpython-36.pyc,, 65 | pyasn1/type/__pycache__/tag.cpython-36.pyc,, 66 | pyasn1/type/__pycache__/tagmap.cpython-36.pyc,, 67 | pyasn1/type/__pycache__/univ.cpython-36.pyc,, 68 | pyasn1/type/__pycache__/useful.cpython-36.pyc,, 69 | pyasn1/type/base.py,sha256=TX7qdOX3EPiY7-11MY4fwK2Hy6nQsrdQ_M41aUcApno,22386 70 | pyasn1/type/char.py,sha256=5HH8r1IqZMDCsfDlQHVCRphLlFuZ93bE2NW78CgeUTI,11397 71 | pyasn1/type/constraint.py,sha256=0Qsth_0JctnDMvOSe5R-vd9IosgjqkKZT_X9lBRXtuI,22132 72 | pyasn1/type/error.py,sha256=4_BHdjX-AL5WMTpU-tX1Nfo_P88c2z1sDvqPU-S9Bns,246 73 | pyasn1/type/namedtype.py,sha256=VIL3H3oPgA0zNrDSeAhKmi4CZGTb69uDBVNJzzRk3wM,16368 74 | pyasn1/type/namedval.py,sha256=dXYWiVTihvBy4RiebGY3AlIXsJvW78mJ1L7JSw-H7Qw,4886 75 | pyasn1/type/opentype.py,sha256=pUpnPqv8o4AFeIsmGHDTFfuxXAq7FvG3hrTEnoAgBO8,2848 76 | pyasn1/type/tag.py,sha256=nAK54C0_F_DL4_IaWRthIfIYBOTuXZoVVcbcbqgZiVA,9486 77 | pyasn1/type/tagmap.py,sha256=2bwm0hqxG2gvXYheOI_iasfl2Z_B93qU7y39EHteUvs,2998 78 | pyasn1/type/univ.py,sha256=FXc_VOStZfC-xIVTznpFO0qTq1aO4XyJFU0ayQWgPMY,108921 79 | pyasn1/type/useful.py,sha256=r_K6UhgcrJ0ej658X-s9522I9T7oYVdmEKcbXTkZMds,5368 80 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1-0.4.8.dist-info/WHEEL: -------------------------------------------------------------------------------- 1 | Wheel-Version: 1.0 2 | Generator: bdist_wheel (0.33.6) 3 | Root-Is-Purelib: true 4 | Tag: py2-none-any 5 | Tag: py3-none-any 6 | 7 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1-0.4.8.dist-info/top_level.txt: -------------------------------------------------------------------------------- 1 | pyasn1 2 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1-0.4.8.dist-info/zip-safe: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/__init__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | # https://www.python.org/dev/peps/pep-0396/ 4 | __version__ = '0.4.8' 5 | 6 | if sys.version_info[:2] < (2, 4): 7 | raise RuntimeError('PyASN1 requires Python 2.4 or later') 8 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/codec/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is necessary to make this directory a package. 2 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/codec/ber/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is necessary to make this directory a package. 2 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/codec/ber/eoo.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | from pyasn1.type import base 8 | from pyasn1.type import tag 9 | 10 | __all__ = ['endOfOctets'] 11 | 12 | 13 | class EndOfOctets(base.SimpleAsn1Type): 14 | defaultValue = 0 15 | tagSet = tag.initTagSet( 16 | tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x00) 17 | ) 18 | 19 | _instance = None 20 | 21 | def __new__(cls, *args, **kwargs): 22 | if cls._instance is None: 23 | cls._instance = object.__new__(cls, *args, **kwargs) 24 | 25 | return cls._instance 26 | 27 | 28 | endOfOctets = EndOfOctets() 29 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/codec/cer/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is necessary to make this directory a package. 2 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/codec/cer/decoder.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | from pyasn1 import error 8 | from pyasn1.codec.ber import decoder 9 | from pyasn1.compat.octets import oct2int 10 | from pyasn1.type import univ 11 | 12 | __all__ = ['decode'] 13 | 14 | 15 | class BooleanDecoder(decoder.AbstractSimpleDecoder): 16 | protoComponent = univ.Boolean(0) 17 | 18 | def valueDecoder(self, substrate, asn1Spec, 19 | tagSet=None, length=None, state=None, 20 | decodeFun=None, substrateFun=None, 21 | **options): 22 | head, tail = substrate[:length], substrate[length:] 23 | if not head or length != 1: 24 | raise error.PyAsn1Error('Not single-octet Boolean payload') 25 | byte = oct2int(head[0]) 26 | # CER/DER specifies encoding of TRUE as 0xFF and FALSE as 0x0, while 27 | # BER allows any non-zero value as TRUE; cf. sections 8.2.2. and 11.1 28 | # in https://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf 29 | if byte == 0xff: 30 | value = 1 31 | elif byte == 0x00: 32 | value = 0 33 | else: 34 | raise error.PyAsn1Error('Unexpected Boolean payload: %s' % byte) 35 | return self._createComponent(asn1Spec, tagSet, value, **options), tail 36 | 37 | # TODO: prohibit non-canonical encoding 38 | BitStringDecoder = decoder.BitStringDecoder 39 | OctetStringDecoder = decoder.OctetStringDecoder 40 | RealDecoder = decoder.RealDecoder 41 | 42 | tagMap = decoder.tagMap.copy() 43 | tagMap.update( 44 | {univ.Boolean.tagSet: BooleanDecoder(), 45 | univ.BitString.tagSet: BitStringDecoder(), 46 | univ.OctetString.tagSet: OctetStringDecoder(), 47 | univ.Real.tagSet: RealDecoder()} 48 | ) 49 | 50 | typeMap = decoder.typeMap.copy() 51 | 52 | # Put in non-ambiguous types for faster codec lookup 53 | for typeDecoder in tagMap.values(): 54 | if typeDecoder.protoComponent is not None: 55 | typeId = typeDecoder.protoComponent.__class__.typeId 56 | if typeId is not None and typeId not in typeMap: 57 | typeMap[typeId] = typeDecoder 58 | 59 | 60 | class Decoder(decoder.Decoder): 61 | pass 62 | 63 | 64 | #: Turns CER octet stream into an ASN.1 object. 65 | #: 66 | #: Takes CER octet-stream and decode it into an ASN.1 object 67 | #: (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative) which 68 | #: may be a scalar or an arbitrary nested structure. 69 | #: 70 | #: Parameters 71 | #: ---------- 72 | #: substrate: :py:class:`bytes` (Python 3) or :py:class:`str` (Python 2) 73 | #: CER octet-stream 74 | #: 75 | #: Keyword Args 76 | #: ------------ 77 | #: asn1Spec: any pyasn1 type object e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative 78 | #: A pyasn1 type object to act as a template guiding the decoder. Depending on the ASN.1 structure 79 | #: being decoded, *asn1Spec* may or may not be required. Most common reason for 80 | #: it to require is that ASN.1 structure is encoded in *IMPLICIT* tagging mode. 81 | #: 82 | #: Returns 83 | #: ------- 84 | #: : :py:class:`tuple` 85 | #: A tuple of pyasn1 object recovered from CER substrate (:py:class:`~pyasn1.type.base.PyAsn1Item` derivative) 86 | #: and the unprocessed trailing portion of the *substrate* (may be empty) 87 | #: 88 | #: Raises 89 | #: ------ 90 | #: ~pyasn1.error.PyAsn1Error, ~pyasn1.error.SubstrateUnderrunError 91 | #: On decoding errors 92 | #: 93 | #: Examples 94 | #: -------- 95 | #: Decode CER serialisation without ASN.1 schema 96 | #: 97 | #: .. code-block:: pycon 98 | #: 99 | #: >>> s, _ = decode(b'0\x80\x02\x01\x01\x02\x01\x02\x02\x01\x03\x00\x00') 100 | #: >>> str(s) 101 | #: SequenceOf: 102 | #: 1 2 3 103 | #: 104 | #: Decode CER serialisation with ASN.1 schema 105 | #: 106 | #: .. code-block:: pycon 107 | #: 108 | #: >>> seq = SequenceOf(componentType=Integer()) 109 | #: >>> s, _ = decode(b'0\x80\x02\x01\x01\x02\x01\x02\x02\x01\x03\x00\x00', asn1Spec=seq) 110 | #: >>> str(s) 111 | #: SequenceOf: 112 | #: 1 2 3 113 | #: 114 | decode = Decoder(tagMap, decoder.typeMap) 115 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/codec/cer/encoder.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | from pyasn1 import error 8 | from pyasn1.codec.ber import encoder 9 | from pyasn1.compat.octets import str2octs, null 10 | from pyasn1.type import univ 11 | from pyasn1.type import useful 12 | 13 | __all__ = ['encode'] 14 | 15 | 16 | class BooleanEncoder(encoder.IntegerEncoder): 17 | def encodeValue(self, value, asn1Spec, encodeFun, **options): 18 | if value == 0: 19 | substrate = (0,) 20 | else: 21 | substrate = (255,) 22 | return substrate, False, False 23 | 24 | 25 | class RealEncoder(encoder.RealEncoder): 26 | def _chooseEncBase(self, value): 27 | m, b, e = value 28 | return self._dropFloatingPoint(m, b, e) 29 | 30 | 31 | # specialized GeneralStringEncoder here 32 | 33 | class TimeEncoderMixIn(object): 34 | Z_CHAR = ord('Z') 35 | PLUS_CHAR = ord('+') 36 | MINUS_CHAR = ord('-') 37 | COMMA_CHAR = ord(',') 38 | DOT_CHAR = ord('.') 39 | ZERO_CHAR = ord('0') 40 | 41 | MIN_LENGTH = 12 42 | MAX_LENGTH = 19 43 | 44 | def encodeValue(self, value, asn1Spec, encodeFun, **options): 45 | # CER encoding constraints: 46 | # - minutes are mandatory, seconds are optional 47 | # - sub-seconds must NOT be zero / no meaningless zeros 48 | # - no hanging fraction dot 49 | # - time in UTC (Z) 50 | # - only dot is allowed for fractions 51 | 52 | if asn1Spec is not None: 53 | value = asn1Spec.clone(value) 54 | 55 | numbers = value.asNumbers() 56 | 57 | if self.PLUS_CHAR in numbers or self.MINUS_CHAR in numbers: 58 | raise error.PyAsn1Error('Must be UTC time: %r' % value) 59 | 60 | if numbers[-1] != self.Z_CHAR: 61 | raise error.PyAsn1Error('Missing "Z" time zone specifier: %r' % value) 62 | 63 | if self.COMMA_CHAR in numbers: 64 | raise error.PyAsn1Error('Comma in fractions disallowed: %r' % value) 65 | 66 | if self.DOT_CHAR in numbers: 67 | 68 | isModified = False 69 | 70 | numbers = list(numbers) 71 | 72 | searchIndex = min(numbers.index(self.DOT_CHAR) + 4, len(numbers) - 1) 73 | 74 | while numbers[searchIndex] != self.DOT_CHAR: 75 | if numbers[searchIndex] == self.ZERO_CHAR: 76 | del numbers[searchIndex] 77 | isModified = True 78 | 79 | searchIndex -= 1 80 | 81 | searchIndex += 1 82 | 83 | if searchIndex < len(numbers): 84 | if numbers[searchIndex] == self.Z_CHAR: 85 | # drop hanging comma 86 | del numbers[searchIndex - 1] 87 | isModified = True 88 | 89 | if isModified: 90 | value = value.clone(numbers) 91 | 92 | if not self.MIN_LENGTH < len(numbers) < self.MAX_LENGTH: 93 | raise error.PyAsn1Error('Length constraint violated: %r' % value) 94 | 95 | options.update(maxChunkSize=1000) 96 | 97 | return encoder.OctetStringEncoder.encodeValue( 98 | self, value, asn1Spec, encodeFun, **options 99 | ) 100 | 101 | 102 | class GeneralizedTimeEncoder(TimeEncoderMixIn, encoder.OctetStringEncoder): 103 | MIN_LENGTH = 12 104 | MAX_LENGTH = 20 105 | 106 | 107 | class UTCTimeEncoder(TimeEncoderMixIn, encoder.OctetStringEncoder): 108 | MIN_LENGTH = 10 109 | MAX_LENGTH = 14 110 | 111 | 112 | class SetOfEncoder(encoder.SequenceOfEncoder): 113 | def encodeValue(self, value, asn1Spec, encodeFun, **options): 114 | chunks = self._encodeComponents( 115 | value, asn1Spec, encodeFun, **options) 116 | 117 | # sort by serialised and padded components 118 | if len(chunks) > 1: 119 | zero = str2octs('\x00') 120 | maxLen = max(map(len, chunks)) 121 | paddedChunks = [ 122 | (x.ljust(maxLen, zero), x) for x in chunks 123 | ] 124 | paddedChunks.sort(key=lambda x: x[0]) 125 | 126 | chunks = [x[1] for x in paddedChunks] 127 | 128 | return null.join(chunks), True, True 129 | 130 | 131 | class SequenceOfEncoder(encoder.SequenceOfEncoder): 132 | def encodeValue(self, value, asn1Spec, encodeFun, **options): 133 | 134 | if options.get('ifNotEmpty', False) and not len(value): 135 | return null, True, True 136 | 137 | chunks = self._encodeComponents( 138 | value, asn1Spec, encodeFun, **options) 139 | 140 | return null.join(chunks), True, True 141 | 142 | 143 | class SetEncoder(encoder.SequenceEncoder): 144 | @staticmethod 145 | def _componentSortKey(componentAndType): 146 | """Sort SET components by tag 147 | 148 | Sort regardless of the Choice value (static sort) 149 | """ 150 | component, asn1Spec = componentAndType 151 | 152 | if asn1Spec is None: 153 | asn1Spec = component 154 | 155 | if asn1Spec.typeId == univ.Choice.typeId and not asn1Spec.tagSet: 156 | if asn1Spec.tagSet: 157 | return asn1Spec.tagSet 158 | else: 159 | return asn1Spec.componentType.minTagSet 160 | else: 161 | return asn1Spec.tagSet 162 | 163 | def encodeValue(self, value, asn1Spec, encodeFun, **options): 164 | 165 | substrate = null 166 | 167 | comps = [] 168 | compsMap = {} 169 | 170 | if asn1Spec is None: 171 | # instance of ASN.1 schema 172 | inconsistency = value.isInconsistent 173 | if inconsistency: 174 | raise inconsistency 175 | 176 | namedTypes = value.componentType 177 | 178 | for idx, component in enumerate(value.values()): 179 | if namedTypes: 180 | namedType = namedTypes[idx] 181 | 182 | if namedType.isOptional and not component.isValue: 183 | continue 184 | 185 | if namedType.isDefaulted and component == namedType.asn1Object: 186 | continue 187 | 188 | compsMap[id(component)] = namedType 189 | 190 | else: 191 | compsMap[id(component)] = None 192 | 193 | comps.append((component, asn1Spec)) 194 | 195 | else: 196 | # bare Python value + ASN.1 schema 197 | for idx, namedType in enumerate(asn1Spec.componentType.namedTypes): 198 | 199 | try: 200 | component = value[namedType.name] 201 | 202 | except KeyError: 203 | raise error.PyAsn1Error('Component name "%s" not found in %r' % (namedType.name, value)) 204 | 205 | if namedType.isOptional and namedType.name not in value: 206 | continue 207 | 208 | if namedType.isDefaulted and component == namedType.asn1Object: 209 | continue 210 | 211 | compsMap[id(component)] = namedType 212 | comps.append((component, asn1Spec[idx])) 213 | 214 | for comp, compType in sorted(comps, key=self._componentSortKey): 215 | namedType = compsMap[id(comp)] 216 | 217 | if namedType: 218 | options.update(ifNotEmpty=namedType.isOptional) 219 | 220 | chunk = encodeFun(comp, compType, **options) 221 | 222 | # wrap open type blob if needed 223 | if namedType and namedType.openType: 224 | wrapType = namedType.asn1Object 225 | if wrapType.tagSet and not wrapType.isSameTypeWith(comp): 226 | chunk = encodeFun(chunk, wrapType, **options) 227 | 228 | substrate += chunk 229 | 230 | return substrate, True, True 231 | 232 | 233 | class SequenceEncoder(encoder.SequenceEncoder): 234 | omitEmptyOptionals = True 235 | 236 | 237 | tagMap = encoder.tagMap.copy() 238 | tagMap.update({ 239 | univ.Boolean.tagSet: BooleanEncoder(), 240 | univ.Real.tagSet: RealEncoder(), 241 | useful.GeneralizedTime.tagSet: GeneralizedTimeEncoder(), 242 | useful.UTCTime.tagSet: UTCTimeEncoder(), 243 | # Sequence & Set have same tags as SequenceOf & SetOf 244 | univ.SetOf.tagSet: SetOfEncoder(), 245 | univ.Sequence.typeId: SequenceEncoder() 246 | }) 247 | 248 | typeMap = encoder.typeMap.copy() 249 | typeMap.update({ 250 | univ.Boolean.typeId: BooleanEncoder(), 251 | univ.Real.typeId: RealEncoder(), 252 | useful.GeneralizedTime.typeId: GeneralizedTimeEncoder(), 253 | useful.UTCTime.typeId: UTCTimeEncoder(), 254 | # Sequence & Set have same tags as SequenceOf & SetOf 255 | univ.Set.typeId: SetEncoder(), 256 | univ.SetOf.typeId: SetOfEncoder(), 257 | univ.Sequence.typeId: SequenceEncoder(), 258 | univ.SequenceOf.typeId: SequenceOfEncoder() 259 | }) 260 | 261 | 262 | class Encoder(encoder.Encoder): 263 | fixedDefLengthMode = False 264 | fixedChunkSize = 1000 265 | 266 | #: Turns ASN.1 object into CER octet stream. 267 | #: 268 | #: Takes any ASN.1 object (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative) 269 | #: walks all its components recursively and produces a CER octet stream. 270 | #: 271 | #: Parameters 272 | #: ---------- 273 | #: value: either a Python or pyasn1 object (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative) 274 | #: A Python or pyasn1 object to encode. If Python object is given, `asnSpec` 275 | #: parameter is required to guide the encoding process. 276 | #: 277 | #: Keyword Args 278 | #: ------------ 279 | #: asn1Spec: 280 | #: Optional ASN.1 schema or value object e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative 281 | #: 282 | #: Returns 283 | #: ------- 284 | #: : :py:class:`bytes` (Python 3) or :py:class:`str` (Python 2) 285 | #: Given ASN.1 object encoded into BER octet-stream 286 | #: 287 | #: Raises 288 | #: ------ 289 | #: ~pyasn1.error.PyAsn1Error 290 | #: On encoding errors 291 | #: 292 | #: Examples 293 | #: -------- 294 | #: Encode Python value into CER with ASN.1 schema 295 | #: 296 | #: .. code-block:: pycon 297 | #: 298 | #: >>> seq = SequenceOf(componentType=Integer()) 299 | #: >>> encode([1, 2, 3], asn1Spec=seq) 300 | #: b'0\x80\x02\x01\x01\x02\x01\x02\x02\x01\x03\x00\x00' 301 | #: 302 | #: Encode ASN.1 value object into CER 303 | #: 304 | #: .. code-block:: pycon 305 | #: 306 | #: >>> seq = SequenceOf(componentType=Integer()) 307 | #: >>> seq.extend([1, 2, 3]) 308 | #: >>> encode(seq) 309 | #: b'0\x80\x02\x01\x01\x02\x01\x02\x02\x01\x03\x00\x00' 310 | #: 311 | encode = Encoder(tagMap, typeMap) 312 | 313 | # EncoderFactory queries class instance and builds a map of tags -> encoders 314 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/codec/der/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is necessary to make this directory a package. 2 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/codec/der/decoder.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | from pyasn1.codec.cer import decoder 8 | from pyasn1.type import univ 9 | 10 | __all__ = ['decode'] 11 | 12 | 13 | class BitStringDecoder(decoder.BitStringDecoder): 14 | supportConstructedForm = False 15 | 16 | 17 | class OctetStringDecoder(decoder.OctetStringDecoder): 18 | supportConstructedForm = False 19 | 20 | # TODO: prohibit non-canonical encoding 21 | RealDecoder = decoder.RealDecoder 22 | 23 | tagMap = decoder.tagMap.copy() 24 | tagMap.update( 25 | {univ.BitString.tagSet: BitStringDecoder(), 26 | univ.OctetString.tagSet: OctetStringDecoder(), 27 | univ.Real.tagSet: RealDecoder()} 28 | ) 29 | 30 | typeMap = decoder.typeMap.copy() 31 | 32 | # Put in non-ambiguous types for faster codec lookup 33 | for typeDecoder in tagMap.values(): 34 | if typeDecoder.protoComponent is not None: 35 | typeId = typeDecoder.protoComponent.__class__.typeId 36 | if typeId is not None and typeId not in typeMap: 37 | typeMap[typeId] = typeDecoder 38 | 39 | 40 | class Decoder(decoder.Decoder): 41 | supportIndefLength = False 42 | 43 | 44 | #: Turns DER octet stream into an ASN.1 object. 45 | #: 46 | #: Takes DER octet-stream and decode it into an ASN.1 object 47 | #: (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative) which 48 | #: may be a scalar or an arbitrary nested structure. 49 | #: 50 | #: Parameters 51 | #: ---------- 52 | #: substrate: :py:class:`bytes` (Python 3) or :py:class:`str` (Python 2) 53 | #: DER octet-stream 54 | #: 55 | #: Keyword Args 56 | #: ------------ 57 | #: asn1Spec: any pyasn1 type object e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative 58 | #: A pyasn1 type object to act as a template guiding the decoder. Depending on the ASN.1 structure 59 | #: being decoded, *asn1Spec* may or may not be required. Most common reason for 60 | #: it to require is that ASN.1 structure is encoded in *IMPLICIT* tagging mode. 61 | #: 62 | #: Returns 63 | #: ------- 64 | #: : :py:class:`tuple` 65 | #: A tuple of pyasn1 object recovered from DER substrate (:py:class:`~pyasn1.type.base.PyAsn1Item` derivative) 66 | #: and the unprocessed trailing portion of the *substrate* (may be empty) 67 | #: 68 | #: Raises 69 | #: ------ 70 | #: ~pyasn1.error.PyAsn1Error, ~pyasn1.error.SubstrateUnderrunError 71 | #: On decoding errors 72 | #: 73 | #: Examples 74 | #: -------- 75 | #: Decode DER serialisation without ASN.1 schema 76 | #: 77 | #: .. code-block:: pycon 78 | #: 79 | #: >>> s, _ = decode(b'0\t\x02\x01\x01\x02\x01\x02\x02\x01\x03') 80 | #: >>> str(s) 81 | #: SequenceOf: 82 | #: 1 2 3 83 | #: 84 | #: Decode DER serialisation with ASN.1 schema 85 | #: 86 | #: .. code-block:: pycon 87 | #: 88 | #: >>> seq = SequenceOf(componentType=Integer()) 89 | #: >>> s, _ = decode(b'0\t\x02\x01\x01\x02\x01\x02\x02\x01\x03', asn1Spec=seq) 90 | #: >>> str(s) 91 | #: SequenceOf: 92 | #: 1 2 3 93 | #: 94 | decode = Decoder(tagMap, typeMap) 95 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/codec/der/encoder.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | from pyasn1 import error 8 | from pyasn1.codec.cer import encoder 9 | from pyasn1.type import univ 10 | 11 | __all__ = ['encode'] 12 | 13 | 14 | class SetEncoder(encoder.SetEncoder): 15 | @staticmethod 16 | def _componentSortKey(componentAndType): 17 | """Sort SET components by tag 18 | 19 | Sort depending on the actual Choice value (dynamic sort) 20 | """ 21 | component, asn1Spec = componentAndType 22 | 23 | if asn1Spec is None: 24 | compType = component 25 | else: 26 | compType = asn1Spec 27 | 28 | if compType.typeId == univ.Choice.typeId and not compType.tagSet: 29 | if asn1Spec is None: 30 | return component.getComponent().tagSet 31 | else: 32 | # TODO: move out of sorting key function 33 | names = [namedType.name for namedType in asn1Spec.componentType.namedTypes 34 | if namedType.name in component] 35 | if len(names) != 1: 36 | raise error.PyAsn1Error( 37 | '%s components for Choice at %r' % (len(names) and 'Multiple ' or 'None ', component)) 38 | 39 | # TODO: support nested CHOICE ordering 40 | return asn1Spec[names[0]].tagSet 41 | 42 | else: 43 | return compType.tagSet 44 | 45 | tagMap = encoder.tagMap.copy() 46 | tagMap.update({ 47 | # Set & SetOf have same tags 48 | univ.Set.tagSet: SetEncoder() 49 | }) 50 | 51 | typeMap = encoder.typeMap.copy() 52 | typeMap.update({ 53 | # Set & SetOf have same tags 54 | univ.Set.typeId: SetEncoder() 55 | }) 56 | 57 | 58 | class Encoder(encoder.Encoder): 59 | fixedDefLengthMode = True 60 | fixedChunkSize = 0 61 | 62 | #: Turns ASN.1 object into DER octet stream. 63 | #: 64 | #: Takes any ASN.1 object (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative) 65 | #: walks all its components recursively and produces a DER octet stream. 66 | #: 67 | #: Parameters 68 | #: ---------- 69 | #: value: either a Python or pyasn1 object (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative) 70 | #: A Python or pyasn1 object to encode. If Python object is given, `asnSpec` 71 | #: parameter is required to guide the encoding process. 72 | #: 73 | #: Keyword Args 74 | #: ------------ 75 | #: asn1Spec: 76 | #: Optional ASN.1 schema or value object e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative 77 | #: 78 | #: Returns 79 | #: ------- 80 | #: : :py:class:`bytes` (Python 3) or :py:class:`str` (Python 2) 81 | #: Given ASN.1 object encoded into BER octet-stream 82 | #: 83 | #: Raises 84 | #: ------ 85 | #: ~pyasn1.error.PyAsn1Error 86 | #: On encoding errors 87 | #: 88 | #: Examples 89 | #: -------- 90 | #: Encode Python value into DER with ASN.1 schema 91 | #: 92 | #: .. code-block:: pycon 93 | #: 94 | #: >>> seq = SequenceOf(componentType=Integer()) 95 | #: >>> encode([1, 2, 3], asn1Spec=seq) 96 | #: b'0\t\x02\x01\x01\x02\x01\x02\x02\x01\x03' 97 | #: 98 | #: Encode ASN.1 value object into DER 99 | #: 100 | #: .. code-block:: pycon 101 | #: 102 | #: >>> seq = SequenceOf(componentType=Integer()) 103 | #: >>> seq.extend([1, 2, 3]) 104 | #: >>> encode(seq) 105 | #: b'0\t\x02\x01\x01\x02\x01\x02\x02\x01\x03' 106 | #: 107 | encode = Encoder(tagMap, typeMap) 108 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/codec/native/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is necessary to make this directory a package. 2 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/codec/native/decoder.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | from pyasn1 import debug 8 | from pyasn1 import error 9 | from pyasn1.type import base 10 | from pyasn1.type import char 11 | from pyasn1.type import tag 12 | from pyasn1.type import univ 13 | from pyasn1.type import useful 14 | 15 | __all__ = ['decode'] 16 | 17 | LOG = debug.registerLoggee(__name__, flags=debug.DEBUG_DECODER) 18 | 19 | 20 | class AbstractScalarDecoder(object): 21 | def __call__(self, pyObject, asn1Spec, decodeFun=None, **options): 22 | return asn1Spec.clone(pyObject) 23 | 24 | 25 | class BitStringDecoder(AbstractScalarDecoder): 26 | def __call__(self, pyObject, asn1Spec, decodeFun=None, **options): 27 | return asn1Spec.clone(univ.BitString.fromBinaryString(pyObject)) 28 | 29 | 30 | class SequenceOrSetDecoder(object): 31 | def __call__(self, pyObject, asn1Spec, decodeFun=None, **options): 32 | asn1Value = asn1Spec.clone() 33 | 34 | componentsTypes = asn1Spec.componentType 35 | 36 | for field in asn1Value: 37 | if field in pyObject: 38 | asn1Value[field] = decodeFun(pyObject[field], componentsTypes[field].asn1Object, **options) 39 | 40 | return asn1Value 41 | 42 | 43 | class SequenceOfOrSetOfDecoder(object): 44 | def __call__(self, pyObject, asn1Spec, decodeFun=None, **options): 45 | asn1Value = asn1Spec.clone() 46 | 47 | for pyValue in pyObject: 48 | asn1Value.append(decodeFun(pyValue, asn1Spec.componentType), **options) 49 | 50 | return asn1Value 51 | 52 | 53 | class ChoiceDecoder(object): 54 | def __call__(self, pyObject, asn1Spec, decodeFun=None, **options): 55 | asn1Value = asn1Spec.clone() 56 | 57 | componentsTypes = asn1Spec.componentType 58 | 59 | for field in pyObject: 60 | if field in componentsTypes: 61 | asn1Value[field] = decodeFun(pyObject[field], componentsTypes[field].asn1Object, **options) 62 | break 63 | 64 | return asn1Value 65 | 66 | 67 | tagMap = { 68 | univ.Integer.tagSet: AbstractScalarDecoder(), 69 | univ.Boolean.tagSet: AbstractScalarDecoder(), 70 | univ.BitString.tagSet: BitStringDecoder(), 71 | univ.OctetString.tagSet: AbstractScalarDecoder(), 72 | univ.Null.tagSet: AbstractScalarDecoder(), 73 | univ.ObjectIdentifier.tagSet: AbstractScalarDecoder(), 74 | univ.Enumerated.tagSet: AbstractScalarDecoder(), 75 | univ.Real.tagSet: AbstractScalarDecoder(), 76 | univ.Sequence.tagSet: SequenceOrSetDecoder(), # conflicts with SequenceOf 77 | univ.Set.tagSet: SequenceOrSetDecoder(), # conflicts with SetOf 78 | univ.Choice.tagSet: ChoiceDecoder(), # conflicts with Any 79 | # character string types 80 | char.UTF8String.tagSet: AbstractScalarDecoder(), 81 | char.NumericString.tagSet: AbstractScalarDecoder(), 82 | char.PrintableString.tagSet: AbstractScalarDecoder(), 83 | char.TeletexString.tagSet: AbstractScalarDecoder(), 84 | char.VideotexString.tagSet: AbstractScalarDecoder(), 85 | char.IA5String.tagSet: AbstractScalarDecoder(), 86 | char.GraphicString.tagSet: AbstractScalarDecoder(), 87 | char.VisibleString.tagSet: AbstractScalarDecoder(), 88 | char.GeneralString.tagSet: AbstractScalarDecoder(), 89 | char.UniversalString.tagSet: AbstractScalarDecoder(), 90 | char.BMPString.tagSet: AbstractScalarDecoder(), 91 | # useful types 92 | useful.ObjectDescriptor.tagSet: AbstractScalarDecoder(), 93 | useful.GeneralizedTime.tagSet: AbstractScalarDecoder(), 94 | useful.UTCTime.tagSet: AbstractScalarDecoder() 95 | } 96 | 97 | # Put in ambiguous & non-ambiguous types for faster codec lookup 98 | typeMap = { 99 | univ.Integer.typeId: AbstractScalarDecoder(), 100 | univ.Boolean.typeId: AbstractScalarDecoder(), 101 | univ.BitString.typeId: BitStringDecoder(), 102 | univ.OctetString.typeId: AbstractScalarDecoder(), 103 | univ.Null.typeId: AbstractScalarDecoder(), 104 | univ.ObjectIdentifier.typeId: AbstractScalarDecoder(), 105 | univ.Enumerated.typeId: AbstractScalarDecoder(), 106 | univ.Real.typeId: AbstractScalarDecoder(), 107 | # ambiguous base types 108 | univ.Set.typeId: SequenceOrSetDecoder(), 109 | univ.SetOf.typeId: SequenceOfOrSetOfDecoder(), 110 | univ.Sequence.typeId: SequenceOrSetDecoder(), 111 | univ.SequenceOf.typeId: SequenceOfOrSetOfDecoder(), 112 | univ.Choice.typeId: ChoiceDecoder(), 113 | univ.Any.typeId: AbstractScalarDecoder(), 114 | # character string types 115 | char.UTF8String.typeId: AbstractScalarDecoder(), 116 | char.NumericString.typeId: AbstractScalarDecoder(), 117 | char.PrintableString.typeId: AbstractScalarDecoder(), 118 | char.TeletexString.typeId: AbstractScalarDecoder(), 119 | char.VideotexString.typeId: AbstractScalarDecoder(), 120 | char.IA5String.typeId: AbstractScalarDecoder(), 121 | char.GraphicString.typeId: AbstractScalarDecoder(), 122 | char.VisibleString.typeId: AbstractScalarDecoder(), 123 | char.GeneralString.typeId: AbstractScalarDecoder(), 124 | char.UniversalString.typeId: AbstractScalarDecoder(), 125 | char.BMPString.typeId: AbstractScalarDecoder(), 126 | # useful types 127 | useful.ObjectDescriptor.typeId: AbstractScalarDecoder(), 128 | useful.GeneralizedTime.typeId: AbstractScalarDecoder(), 129 | useful.UTCTime.typeId: AbstractScalarDecoder() 130 | } 131 | 132 | 133 | class Decoder(object): 134 | 135 | # noinspection PyDefaultArgument 136 | def __init__(self, tagMap, typeMap): 137 | self.__tagMap = tagMap 138 | self.__typeMap = typeMap 139 | 140 | def __call__(self, pyObject, asn1Spec, **options): 141 | 142 | if LOG: 143 | debug.scope.push(type(pyObject).__name__) 144 | LOG('decoder called at scope %s, working with type %s' % (debug.scope, type(pyObject).__name__)) 145 | 146 | if asn1Spec is None or not isinstance(asn1Spec, base.Asn1Item): 147 | raise error.PyAsn1Error('asn1Spec is not valid (should be an instance of an ASN.1 Item, not %s)' % asn1Spec.__class__.__name__) 148 | 149 | try: 150 | valueDecoder = self.__typeMap[asn1Spec.typeId] 151 | 152 | except KeyError: 153 | # use base type for codec lookup to recover untagged types 154 | baseTagSet = tag.TagSet(asn1Spec.tagSet.baseTag, asn1Spec.tagSet.baseTag) 155 | 156 | try: 157 | valueDecoder = self.__tagMap[baseTagSet] 158 | except KeyError: 159 | raise error.PyAsn1Error('Unknown ASN.1 tag %s' % asn1Spec.tagSet) 160 | 161 | if LOG: 162 | LOG('calling decoder %s on Python type %s <%s>' % (type(valueDecoder).__name__, type(pyObject).__name__, repr(pyObject))) 163 | 164 | value = valueDecoder(pyObject, asn1Spec, self, **options) 165 | 166 | if LOG: 167 | LOG('decoder %s produced ASN.1 type %s <%s>' % (type(valueDecoder).__name__, type(value).__name__, repr(value))) 168 | debug.scope.pop() 169 | 170 | return value 171 | 172 | 173 | #: Turns Python objects of built-in types into ASN.1 objects. 174 | #: 175 | #: Takes Python objects of built-in types and turns them into a tree of 176 | #: ASN.1 objects (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative) which 177 | #: may be a scalar or an arbitrary nested structure. 178 | #: 179 | #: Parameters 180 | #: ---------- 181 | #: pyObject: :py:class:`object` 182 | #: A scalar or nested Python objects 183 | #: 184 | #: Keyword Args 185 | #: ------------ 186 | #: asn1Spec: any pyasn1 type object e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative 187 | #: A pyasn1 type object to act as a template guiding the decoder. It is required 188 | #: for successful interpretation of Python objects mapping into their ASN.1 189 | #: representations. 190 | #: 191 | #: Returns 192 | #: ------- 193 | #: : :py:class:`~pyasn1.type.base.PyAsn1Item` derivative 194 | #: A scalar or constructed pyasn1 object 195 | #: 196 | #: Raises 197 | #: ------ 198 | #: ~pyasn1.error.PyAsn1Error 199 | #: On decoding errors 200 | #: 201 | #: Examples 202 | #: -------- 203 | #: Decode native Python object into ASN.1 objects with ASN.1 schema 204 | #: 205 | #: .. code-block:: pycon 206 | #: 207 | #: >>> seq = SequenceOf(componentType=Integer()) 208 | #: >>> s, _ = decode([1, 2, 3], asn1Spec=seq) 209 | #: >>> str(s) 210 | #: SequenceOf: 211 | #: 1 2 3 212 | #: 213 | decode = Decoder(tagMap, typeMap) 214 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/codec/native/encoder.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | try: 8 | from collections import OrderedDict 9 | 10 | except ImportError: 11 | OrderedDict = dict 12 | 13 | from pyasn1 import debug 14 | from pyasn1 import error 15 | from pyasn1.type import base 16 | from pyasn1.type import char 17 | from pyasn1.type import tag 18 | from pyasn1.type import univ 19 | from pyasn1.type import useful 20 | 21 | __all__ = ['encode'] 22 | 23 | LOG = debug.registerLoggee(__name__, flags=debug.DEBUG_ENCODER) 24 | 25 | 26 | class AbstractItemEncoder(object): 27 | def encode(self, value, encodeFun, **options): 28 | raise error.PyAsn1Error('Not implemented') 29 | 30 | 31 | class BooleanEncoder(AbstractItemEncoder): 32 | def encode(self, value, encodeFun, **options): 33 | return bool(value) 34 | 35 | 36 | class IntegerEncoder(AbstractItemEncoder): 37 | def encode(self, value, encodeFun, **options): 38 | return int(value) 39 | 40 | 41 | class BitStringEncoder(AbstractItemEncoder): 42 | def encode(self, value, encodeFun, **options): 43 | return str(value) 44 | 45 | 46 | class OctetStringEncoder(AbstractItemEncoder): 47 | def encode(self, value, encodeFun, **options): 48 | return value.asOctets() 49 | 50 | 51 | class TextStringEncoder(AbstractItemEncoder): 52 | def encode(self, value, encodeFun, **options): 53 | return str(value) 54 | 55 | 56 | class NullEncoder(AbstractItemEncoder): 57 | def encode(self, value, encodeFun, **options): 58 | return None 59 | 60 | 61 | class ObjectIdentifierEncoder(AbstractItemEncoder): 62 | def encode(self, value, encodeFun, **options): 63 | return str(value) 64 | 65 | 66 | class RealEncoder(AbstractItemEncoder): 67 | def encode(self, value, encodeFun, **options): 68 | return float(value) 69 | 70 | 71 | class SetEncoder(AbstractItemEncoder): 72 | protoDict = dict 73 | 74 | def encode(self, value, encodeFun, **options): 75 | inconsistency = value.isInconsistent 76 | if inconsistency: 77 | raise inconsistency 78 | 79 | namedTypes = value.componentType 80 | substrate = self.protoDict() 81 | 82 | for idx, (key, subValue) in enumerate(value.items()): 83 | if namedTypes and namedTypes[idx].isOptional and not value[idx].isValue: 84 | continue 85 | substrate[key] = encodeFun(subValue, **options) 86 | return substrate 87 | 88 | 89 | class SequenceEncoder(SetEncoder): 90 | protoDict = OrderedDict 91 | 92 | 93 | class SequenceOfEncoder(AbstractItemEncoder): 94 | def encode(self, value, encodeFun, **options): 95 | inconsistency = value.isInconsistent 96 | if inconsistency: 97 | raise inconsistency 98 | return [encodeFun(x, **options) for x in value] 99 | 100 | 101 | class ChoiceEncoder(SequenceEncoder): 102 | pass 103 | 104 | 105 | class AnyEncoder(AbstractItemEncoder): 106 | def encode(self, value, encodeFun, **options): 107 | return value.asOctets() 108 | 109 | 110 | tagMap = { 111 | univ.Boolean.tagSet: BooleanEncoder(), 112 | univ.Integer.tagSet: IntegerEncoder(), 113 | univ.BitString.tagSet: BitStringEncoder(), 114 | univ.OctetString.tagSet: OctetStringEncoder(), 115 | univ.Null.tagSet: NullEncoder(), 116 | univ.ObjectIdentifier.tagSet: ObjectIdentifierEncoder(), 117 | univ.Enumerated.tagSet: IntegerEncoder(), 118 | univ.Real.tagSet: RealEncoder(), 119 | # Sequence & Set have same tags as SequenceOf & SetOf 120 | univ.SequenceOf.tagSet: SequenceOfEncoder(), 121 | univ.SetOf.tagSet: SequenceOfEncoder(), 122 | univ.Choice.tagSet: ChoiceEncoder(), 123 | # character string types 124 | char.UTF8String.tagSet: TextStringEncoder(), 125 | char.NumericString.tagSet: TextStringEncoder(), 126 | char.PrintableString.tagSet: TextStringEncoder(), 127 | char.TeletexString.tagSet: TextStringEncoder(), 128 | char.VideotexString.tagSet: TextStringEncoder(), 129 | char.IA5String.tagSet: TextStringEncoder(), 130 | char.GraphicString.tagSet: TextStringEncoder(), 131 | char.VisibleString.tagSet: TextStringEncoder(), 132 | char.GeneralString.tagSet: TextStringEncoder(), 133 | char.UniversalString.tagSet: TextStringEncoder(), 134 | char.BMPString.tagSet: TextStringEncoder(), 135 | # useful types 136 | useful.ObjectDescriptor.tagSet: OctetStringEncoder(), 137 | useful.GeneralizedTime.tagSet: OctetStringEncoder(), 138 | useful.UTCTime.tagSet: OctetStringEncoder() 139 | } 140 | 141 | 142 | # Put in ambiguous & non-ambiguous types for faster codec lookup 143 | typeMap = { 144 | univ.Boolean.typeId: BooleanEncoder(), 145 | univ.Integer.typeId: IntegerEncoder(), 146 | univ.BitString.typeId: BitStringEncoder(), 147 | univ.OctetString.typeId: OctetStringEncoder(), 148 | univ.Null.typeId: NullEncoder(), 149 | univ.ObjectIdentifier.typeId: ObjectIdentifierEncoder(), 150 | univ.Enumerated.typeId: IntegerEncoder(), 151 | univ.Real.typeId: RealEncoder(), 152 | # Sequence & Set have same tags as SequenceOf & SetOf 153 | univ.Set.typeId: SetEncoder(), 154 | univ.SetOf.typeId: SequenceOfEncoder(), 155 | univ.Sequence.typeId: SequenceEncoder(), 156 | univ.SequenceOf.typeId: SequenceOfEncoder(), 157 | univ.Choice.typeId: ChoiceEncoder(), 158 | univ.Any.typeId: AnyEncoder(), 159 | # character string types 160 | char.UTF8String.typeId: OctetStringEncoder(), 161 | char.NumericString.typeId: OctetStringEncoder(), 162 | char.PrintableString.typeId: OctetStringEncoder(), 163 | char.TeletexString.typeId: OctetStringEncoder(), 164 | char.VideotexString.typeId: OctetStringEncoder(), 165 | char.IA5String.typeId: OctetStringEncoder(), 166 | char.GraphicString.typeId: OctetStringEncoder(), 167 | char.VisibleString.typeId: OctetStringEncoder(), 168 | char.GeneralString.typeId: OctetStringEncoder(), 169 | char.UniversalString.typeId: OctetStringEncoder(), 170 | char.BMPString.typeId: OctetStringEncoder(), 171 | # useful types 172 | useful.ObjectDescriptor.typeId: OctetStringEncoder(), 173 | useful.GeneralizedTime.typeId: OctetStringEncoder(), 174 | useful.UTCTime.typeId: OctetStringEncoder() 175 | } 176 | 177 | 178 | class Encoder(object): 179 | 180 | # noinspection PyDefaultArgument 181 | def __init__(self, tagMap, typeMap={}): 182 | self.__tagMap = tagMap 183 | self.__typeMap = typeMap 184 | 185 | def __call__(self, value, **options): 186 | if not isinstance(value, base.Asn1Item): 187 | raise error.PyAsn1Error('value is not valid (should be an instance of an ASN.1 Item)') 188 | 189 | if LOG: 190 | debug.scope.push(type(value).__name__) 191 | LOG('encoder called for type %s <%s>' % (type(value).__name__, value.prettyPrint())) 192 | 193 | tagSet = value.tagSet 194 | 195 | try: 196 | concreteEncoder = self.__typeMap[value.typeId] 197 | 198 | except KeyError: 199 | # use base type for codec lookup to recover untagged types 200 | baseTagSet = tag.TagSet(value.tagSet.baseTag, value.tagSet.baseTag) 201 | 202 | try: 203 | concreteEncoder = self.__tagMap[baseTagSet] 204 | 205 | except KeyError: 206 | raise error.PyAsn1Error('No encoder for %s' % (value,)) 207 | 208 | if LOG: 209 | LOG('using value codec %s chosen by %s' % (concreteEncoder.__class__.__name__, tagSet)) 210 | 211 | pyObject = concreteEncoder.encode(value, self, **options) 212 | 213 | if LOG: 214 | LOG('encoder %s produced: %s' % (type(concreteEncoder).__name__, repr(pyObject))) 215 | debug.scope.pop() 216 | 217 | return pyObject 218 | 219 | 220 | #: Turns ASN.1 object into a Python built-in type object(s). 221 | #: 222 | #: Takes any ASN.1 object (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative) 223 | #: walks all its components recursively and produces a Python built-in type or a tree 224 | #: of those. 225 | #: 226 | #: One exception is that instead of :py:class:`dict`, the :py:class:`OrderedDict` 227 | #: can be produced (whenever available) to preserve ordering of the components 228 | #: in ASN.1 SEQUENCE. 229 | #: 230 | #: Parameters 231 | #: ---------- 232 | # asn1Value: any pyasn1 object (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative) 233 | #: pyasn1 object to encode (or a tree of them) 234 | #: 235 | #: Returns 236 | #: ------- 237 | #: : :py:class:`object` 238 | #: Python built-in type instance (or a tree of them) 239 | #: 240 | #: Raises 241 | #: ------ 242 | #: ~pyasn1.error.PyAsn1Error 243 | #: On encoding errors 244 | #: 245 | #: Examples 246 | #: -------- 247 | #: Encode ASN.1 value object into native Python types 248 | #: 249 | #: .. code-block:: pycon 250 | #: 251 | #: >>> seq = SequenceOf(componentType=Integer()) 252 | #: >>> seq.extend([1, 2, 3]) 253 | #: >>> encode(seq) 254 | #: [1, 2, 3] 255 | #: 256 | encode = Encoder(tagMap, typeMap) 257 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/compat/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is necessary to make this directory a package. 2 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/compat/binary.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | from sys import version_info 8 | 9 | if version_info[0:2] < (2, 6): 10 | def bin(value): 11 | bitstring = [] 12 | 13 | if value > 0: 14 | prefix = '0b' 15 | elif value < 0: 16 | prefix = '-0b' 17 | value = abs(value) 18 | else: 19 | prefix = '0b0' 20 | 21 | while value: 22 | if value & 1 == 1: 23 | bitstring.append('1') 24 | else: 25 | bitstring.append('0') 26 | 27 | value >>= 1 28 | 29 | bitstring.reverse() 30 | 31 | return prefix + ''.join(bitstring) 32 | else: 33 | bin = bin 34 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/compat/calling.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | from sys import version_info 8 | 9 | __all__ = ['callable'] 10 | 11 | 12 | if (2, 7) < version_info[:2] < (3, 2): 13 | import collections 14 | 15 | def callable(x): 16 | return isinstance(x, collections.Callable) 17 | 18 | else: 19 | 20 | callable = callable 21 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/compat/dateandtime.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | import time 8 | from datetime import datetime 9 | from sys import version_info 10 | 11 | __all__ = ['strptime'] 12 | 13 | 14 | if version_info[:2] <= (2, 4): 15 | 16 | def strptime(text, dateFormat): 17 | return datetime(*(time.strptime(text, dateFormat)[0:6])) 18 | 19 | else: 20 | 21 | def strptime(text, dateFormat): 22 | return datetime.strptime(text, dateFormat) 23 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/compat/integer.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | import sys 8 | 9 | try: 10 | import platform 11 | 12 | implementation = platform.python_implementation() 13 | 14 | except (ImportError, AttributeError): 15 | implementation = 'CPython' 16 | 17 | from pyasn1.compat.octets import oct2int, null, ensureString 18 | 19 | if sys.version_info[0:2] < (3, 2) or implementation != 'CPython': 20 | from binascii import a2b_hex, b2a_hex 21 | 22 | if sys.version_info[0] > 2: 23 | long = int 24 | 25 | def from_bytes(octets, signed=False): 26 | if not octets: 27 | return 0 28 | 29 | value = long(b2a_hex(ensureString(octets)), 16) 30 | 31 | if signed and oct2int(octets[0]) & 0x80: 32 | return value - (1 << len(octets) * 8) 33 | 34 | return value 35 | 36 | def to_bytes(value, signed=False, length=0): 37 | if value < 0: 38 | if signed: 39 | bits = bitLength(value) 40 | 41 | # two's complement form 42 | maxValue = 1 << bits 43 | valueToEncode = (value + maxValue) % maxValue 44 | 45 | else: 46 | raise OverflowError('can\'t convert negative int to unsigned') 47 | elif value == 0 and length == 0: 48 | return null 49 | else: 50 | bits = 0 51 | valueToEncode = value 52 | 53 | hexValue = hex(valueToEncode)[2:] 54 | if hexValue.endswith('L'): 55 | hexValue = hexValue[:-1] 56 | 57 | if len(hexValue) & 1: 58 | hexValue = '0' + hexValue 59 | 60 | # padding may be needed for two's complement encoding 61 | if value != valueToEncode or length: 62 | hexLength = len(hexValue) * 4 63 | 64 | padLength = max(length, bits) 65 | 66 | if padLength > hexLength: 67 | hexValue = '00' * ((padLength - hexLength - 1) // 8 + 1) + hexValue 68 | elif length and hexLength - length > 7: 69 | raise OverflowError('int too big to convert') 70 | 71 | firstOctet = int(hexValue[:2], 16) 72 | 73 | if signed: 74 | if firstOctet & 0x80: 75 | if value >= 0: 76 | hexValue = '00' + hexValue 77 | elif value < 0: 78 | hexValue = 'ff' + hexValue 79 | 80 | octets_value = a2b_hex(hexValue) 81 | 82 | return octets_value 83 | 84 | def bitLength(number): 85 | # bits in unsigned number 86 | hexValue = hex(abs(number)) 87 | bits = len(hexValue) - 2 88 | if hexValue.endswith('L'): 89 | bits -= 1 90 | if bits & 1: 91 | bits += 1 92 | bits *= 4 93 | # TODO: strip lhs zeros 94 | return bits 95 | 96 | else: 97 | 98 | def from_bytes(octets, signed=False): 99 | return int.from_bytes(bytes(octets), 'big', signed=signed) 100 | 101 | def to_bytes(value, signed=False, length=0): 102 | length = max(value.bit_length(), length) 103 | 104 | if signed and length % 8 == 0: 105 | length += 1 106 | 107 | return value.to_bytes(length // 8 + (length % 8 and 1 or 0), 'big', signed=signed) 108 | 109 | def bitLength(number): 110 | return int(number).bit_length() 111 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/compat/octets.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | from sys import version_info 8 | 9 | if version_info[0] <= 2: 10 | int2oct = chr 11 | # noinspection PyPep8 12 | ints2octs = lambda s: ''.join([int2oct(x) for x in s]) 13 | null = '' 14 | oct2int = ord 15 | # TODO: refactor to return a sequence of ints 16 | # noinspection PyPep8 17 | octs2ints = lambda s: [oct2int(x) for x in s] 18 | # noinspection PyPep8 19 | str2octs = lambda x: x 20 | # noinspection PyPep8 21 | octs2str = lambda x: x 22 | # noinspection PyPep8 23 | isOctetsType = lambda s: isinstance(s, str) 24 | # noinspection PyPep8 25 | isStringType = lambda s: isinstance(s, (str, unicode)) 26 | # noinspection PyPep8 27 | ensureString = str 28 | else: 29 | ints2octs = bytes 30 | # noinspection PyPep8 31 | int2oct = lambda x: ints2octs((x,)) 32 | null = ints2octs() 33 | # noinspection PyPep8 34 | oct2int = lambda x: x 35 | # noinspection PyPep8 36 | octs2ints = lambda x: x 37 | # noinspection PyPep8 38 | str2octs = lambda x: x.encode('iso-8859-1') 39 | # noinspection PyPep8 40 | octs2str = lambda x: x.decode('iso-8859-1') 41 | # noinspection PyPep8 42 | isOctetsType = lambda s: isinstance(s, bytes) 43 | # noinspection PyPep8 44 | isStringType = lambda s: isinstance(s, str) 45 | # noinspection PyPep8 46 | ensureString = bytes 47 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/compat/string.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | from sys import version_info 8 | 9 | if version_info[:2] <= (2, 5): 10 | 11 | def partition(string, sep): 12 | try: 13 | a, c = string.split(sep, 1) 14 | 15 | except ValueError: 16 | a, b, c = string, '', '' 17 | 18 | else: 19 | b = sep 20 | 21 | return a, b, c 22 | 23 | else: 24 | 25 | def partition(string, sep): 26 | return string.partition(sep) 27 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/debug.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | import logging 8 | import sys 9 | 10 | from pyasn1 import __version__ 11 | from pyasn1 import error 12 | from pyasn1.compat.octets import octs2ints 13 | 14 | __all__ = ['Debug', 'setLogger', 'hexdump'] 15 | 16 | DEBUG_NONE = 0x0000 17 | DEBUG_ENCODER = 0x0001 18 | DEBUG_DECODER = 0x0002 19 | DEBUG_ALL = 0xffff 20 | 21 | FLAG_MAP = { 22 | 'none': DEBUG_NONE, 23 | 'encoder': DEBUG_ENCODER, 24 | 'decoder': DEBUG_DECODER, 25 | 'all': DEBUG_ALL 26 | } 27 | 28 | LOGGEE_MAP = {} 29 | 30 | 31 | class Printer(object): 32 | # noinspection PyShadowingNames 33 | def __init__(self, logger=None, handler=None, formatter=None): 34 | if logger is None: 35 | logger = logging.getLogger('pyasn1') 36 | 37 | logger.setLevel(logging.DEBUG) 38 | 39 | if handler is None: 40 | handler = logging.StreamHandler() 41 | 42 | if formatter is None: 43 | formatter = logging.Formatter('%(asctime)s %(name)s: %(message)s') 44 | 45 | handler.setFormatter(formatter) 46 | handler.setLevel(logging.DEBUG) 47 | logger.addHandler(handler) 48 | 49 | self.__logger = logger 50 | 51 | def __call__(self, msg): 52 | self.__logger.debug(msg) 53 | 54 | def __str__(self): 55 | return '' 56 | 57 | 58 | if hasattr(logging, 'NullHandler'): 59 | NullHandler = logging.NullHandler 60 | 61 | else: 62 | # Python 2.6 and older 63 | class NullHandler(logging.Handler): 64 | def emit(self, record): 65 | pass 66 | 67 | 68 | class Debug(object): 69 | defaultPrinter = Printer() 70 | 71 | def __init__(self, *flags, **options): 72 | self._flags = DEBUG_NONE 73 | 74 | if 'loggerName' in options: 75 | # route our logs to parent logger 76 | self._printer = Printer( 77 | logger=logging.getLogger(options['loggerName']), 78 | handler=NullHandler() 79 | ) 80 | 81 | elif 'printer' in options: 82 | self._printer = options.get('printer') 83 | 84 | else: 85 | self._printer = self.defaultPrinter 86 | 87 | self._printer('running pyasn1 %s, debug flags %s' % (__version__, ', '.join(flags))) 88 | 89 | for flag in flags: 90 | inverse = flag and flag[0] in ('!', '~') 91 | if inverse: 92 | flag = flag[1:] 93 | try: 94 | if inverse: 95 | self._flags &= ~FLAG_MAP[flag] 96 | else: 97 | self._flags |= FLAG_MAP[flag] 98 | except KeyError: 99 | raise error.PyAsn1Error('bad debug flag %s' % flag) 100 | 101 | self._printer("debug category '%s' %s" % (flag, inverse and 'disabled' or 'enabled')) 102 | 103 | def __str__(self): 104 | return 'logger %s, flags %x' % (self._printer, self._flags) 105 | 106 | def __call__(self, msg): 107 | self._printer(msg) 108 | 109 | def __and__(self, flag): 110 | return self._flags & flag 111 | 112 | def __rand__(self, flag): 113 | return flag & self._flags 114 | 115 | _LOG = DEBUG_NONE 116 | 117 | 118 | def setLogger(userLogger): 119 | global _LOG 120 | 121 | if userLogger: 122 | _LOG = userLogger 123 | else: 124 | _LOG = DEBUG_NONE 125 | 126 | # Update registered logging clients 127 | for module, (name, flags) in LOGGEE_MAP.items(): 128 | setattr(module, name, _LOG & flags and _LOG or DEBUG_NONE) 129 | 130 | 131 | def registerLoggee(module, name='LOG', flags=DEBUG_NONE): 132 | LOGGEE_MAP[sys.modules[module]] = name, flags 133 | setLogger(_LOG) 134 | return _LOG 135 | 136 | 137 | def hexdump(octets): 138 | return ' '.join( 139 | ['%s%.2X' % (n % 16 == 0 and ('\n%.5d: ' % n) or '', x) 140 | for n, x in zip(range(len(octets)), octs2ints(octets))] 141 | ) 142 | 143 | 144 | class Scope(object): 145 | def __init__(self): 146 | self._list = [] 147 | 148 | def __str__(self): return '.'.join(self._list) 149 | 150 | def push(self, token): 151 | self._list.append(token) 152 | 153 | def pop(self): 154 | return self._list.pop() 155 | 156 | 157 | scope = Scope() 158 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/error.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | 8 | 9 | class PyAsn1Error(Exception): 10 | """Base pyasn1 exception 11 | 12 | `PyAsn1Error` is the base exception class (based on 13 | :class:`Exception`) that represents all possible ASN.1 related 14 | errors. 15 | """ 16 | 17 | 18 | class ValueConstraintError(PyAsn1Error): 19 | """ASN.1 type constraints violation exception 20 | 21 | The `ValueConstraintError` exception indicates an ASN.1 value 22 | constraint violation. 23 | 24 | It might happen on value object instantiation (for scalar types) or on 25 | serialization (for constructed types). 26 | """ 27 | 28 | 29 | class SubstrateUnderrunError(PyAsn1Error): 30 | """ASN.1 data structure deserialization error 31 | 32 | The `SubstrateUnderrunError` exception indicates insufficient serialised 33 | data on input of a de-serialization codec. 34 | """ 35 | 36 | 37 | class PyAsn1UnicodeError(PyAsn1Error, UnicodeError): 38 | """Unicode text processing error 39 | 40 | The `PyAsn1UnicodeError` exception is a base class for errors relating to 41 | unicode text de/serialization. 42 | 43 | Apart from inheriting from :class:`PyAsn1Error`, it also inherits from 44 | :class:`UnicodeError` to help the caller catching unicode-related errors. 45 | """ 46 | def __init__(self, message, unicode_error=None): 47 | if isinstance(unicode_error, UnicodeError): 48 | UnicodeError.__init__(self, *unicode_error.args) 49 | PyAsn1Error.__init__(self, message) 50 | 51 | 52 | class PyAsn1UnicodeDecodeError(PyAsn1UnicodeError, UnicodeDecodeError): 53 | """Unicode text decoding error 54 | 55 | The `PyAsn1UnicodeDecodeError` exception represents a failure to 56 | deserialize unicode text. 57 | 58 | Apart from inheriting from :class:`PyAsn1UnicodeError`, it also inherits 59 | from :class:`UnicodeDecodeError` to help the caller catching unicode-related 60 | errors. 61 | """ 62 | 63 | 64 | class PyAsn1UnicodeEncodeError(PyAsn1UnicodeError, UnicodeEncodeError): 65 | """Unicode text encoding error 66 | 67 | The `PyAsn1UnicodeEncodeError` exception represents a failure to 68 | serialize unicode text. 69 | 70 | Apart from inheriting from :class:`PyAsn1UnicodeError`, it also inherits 71 | from :class:`UnicodeEncodeError` to help the caller catching 72 | unicode-related errors. 73 | """ 74 | 75 | 76 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/type/__init__.py: -------------------------------------------------------------------------------- 1 | # This file is necessary to make this directory a package. 2 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/type/error.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | from pyasn1.error import PyAsn1Error 8 | 9 | 10 | class ValueConstraintError(PyAsn1Error): 11 | pass 12 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/type/namedval.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | # ASN.1 named integers 8 | # 9 | from pyasn1 import error 10 | 11 | __all__ = ['NamedValues'] 12 | 13 | 14 | class NamedValues(object): 15 | """Create named values object. 16 | 17 | The |NamedValues| object represents a collection of string names 18 | associated with numeric IDs. These objects are used for giving 19 | names to otherwise numerical values. 20 | 21 | |NamedValues| objects are immutable and duck-type Python 22 | :class:`dict` object mapping ID to name and vice-versa. 23 | 24 | Parameters 25 | ---------- 26 | *args: variable number of two-element :py:class:`tuple` 27 | 28 | name: :py:class:`str` 29 | Value label 30 | 31 | value: :py:class:`int` 32 | Numeric value 33 | 34 | Keyword Args 35 | ------------ 36 | name: :py:class:`str` 37 | Value label 38 | 39 | value: :py:class:`int` 40 | Numeric value 41 | 42 | Examples 43 | -------- 44 | 45 | .. code-block:: pycon 46 | 47 | >>> nv = NamedValues('a', 'b', ('c', 0), d=1) 48 | >>> nv 49 | >>> {'c': 0, 'd': 1, 'a': 2, 'b': 3} 50 | >>> nv[0] 51 | 'c' 52 | >>> nv['a'] 53 | 2 54 | """ 55 | def __init__(self, *args, **kwargs): 56 | self.__names = {} 57 | self.__numbers = {} 58 | 59 | anonymousNames = [] 60 | 61 | for namedValue in args: 62 | if isinstance(namedValue, (tuple, list)): 63 | try: 64 | name, number = namedValue 65 | 66 | except ValueError: 67 | raise error.PyAsn1Error('Not a proper attribute-value pair %r' % (namedValue,)) 68 | 69 | else: 70 | anonymousNames.append(namedValue) 71 | continue 72 | 73 | if name in self.__names: 74 | raise error.PyAsn1Error('Duplicate name %s' % (name,)) 75 | 76 | if number in self.__numbers: 77 | raise error.PyAsn1Error('Duplicate number %s=%s' % (name, number)) 78 | 79 | self.__names[name] = number 80 | self.__numbers[number] = name 81 | 82 | for name, number in kwargs.items(): 83 | if name in self.__names: 84 | raise error.PyAsn1Error('Duplicate name %s' % (name,)) 85 | 86 | if number in self.__numbers: 87 | raise error.PyAsn1Error('Duplicate number %s=%s' % (name, number)) 88 | 89 | self.__names[name] = number 90 | self.__numbers[number] = name 91 | 92 | if anonymousNames: 93 | 94 | number = self.__numbers and max(self.__numbers) + 1 or 0 95 | 96 | for name in anonymousNames: 97 | 98 | if name in self.__names: 99 | raise error.PyAsn1Error('Duplicate name %s' % (name,)) 100 | 101 | self.__names[name] = number 102 | self.__numbers[number] = name 103 | 104 | number += 1 105 | 106 | def __repr__(self): 107 | representation = ', '.join(['%s=%d' % x for x in self.items()]) 108 | 109 | if len(representation) > 64: 110 | representation = representation[:32] + '...' + representation[-32:] 111 | 112 | return '<%s object, enums %s>' % ( 113 | self.__class__.__name__, representation) 114 | 115 | def __eq__(self, other): 116 | return dict(self) == other 117 | 118 | def __ne__(self, other): 119 | return dict(self) != other 120 | 121 | def __lt__(self, other): 122 | return dict(self) < other 123 | 124 | def __le__(self, other): 125 | return dict(self) <= other 126 | 127 | def __gt__(self, other): 128 | return dict(self) > other 129 | 130 | def __ge__(self, other): 131 | return dict(self) >= other 132 | 133 | def __hash__(self): 134 | return hash(self.items()) 135 | 136 | # Python dict protocol (read-only) 137 | 138 | def __getitem__(self, key): 139 | try: 140 | return self.__numbers[key] 141 | 142 | except KeyError: 143 | return self.__names[key] 144 | 145 | def __len__(self): 146 | return len(self.__names) 147 | 148 | def __contains__(self, key): 149 | return key in self.__names or key in self.__numbers 150 | 151 | def __iter__(self): 152 | return iter(self.__names) 153 | 154 | def values(self): 155 | return iter(self.__numbers) 156 | 157 | def keys(self): 158 | return iter(self.__names) 159 | 160 | def items(self): 161 | for name in self.__names: 162 | yield name, self.__names[name] 163 | 164 | # support merging 165 | 166 | def __add__(self, namedValues): 167 | return self.__class__(*tuple(self.items()) + tuple(namedValues.items())) 168 | 169 | # XXX clone/subtype? 170 | 171 | def clone(self, *args, **kwargs): 172 | new = self.__class__(*args, **kwargs) 173 | return self + new 174 | 175 | # legacy protocol 176 | 177 | def getName(self, value): 178 | if value in self.__numbers: 179 | return self.__numbers[value] 180 | 181 | def getValue(self, name): 182 | if name in self.__names: 183 | return self.__names[name] 184 | 185 | def getValues(self, *names): 186 | try: 187 | return [self.__names[name] for name in names] 188 | 189 | except KeyError: 190 | raise error.PyAsn1Error( 191 | 'Unknown bit identifier(s): %s' % (set(names).difference(self.__names),) 192 | ) 193 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/type/opentype.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | 8 | __all__ = ['OpenType'] 9 | 10 | 11 | class OpenType(object): 12 | """Create ASN.1 type map indexed by a value 13 | 14 | The *OpenType* object models an untyped field of a constructed ASN.1 15 | type. In ASN.1 syntax it is usually represented by the 16 | `ANY DEFINED BY` for scalars or `SET OF ANY DEFINED BY`, 17 | `SEQUENCE OF ANY DEFINED BY` for container types clauses. Typically 18 | used together with :class:`~pyasn1.type.univ.Any` object. 19 | 20 | OpenType objects duck-type a read-only Python :class:`dict` objects, 21 | however the passed `typeMap` is not copied, but stored by reference. 22 | That means the user can manipulate `typeMap` at run time having this 23 | reflected on *OpenType* object behavior. 24 | 25 | The |OpenType| class models an untyped field of a constructed ASN.1 26 | type. In ASN.1 syntax it is usually represented by the 27 | `ANY DEFINED BY` for scalars or `SET OF ANY DEFINED BY`, 28 | `SEQUENCE OF ANY DEFINED BY` for container types clauses. Typically 29 | used with :class:`~pyasn1.type.univ.Any` type. 30 | 31 | Parameters 32 | ---------- 33 | name: :py:class:`str` 34 | Field name 35 | 36 | typeMap: :py:class:`dict` 37 | A map of value->ASN.1 type. It's stored by reference and can be 38 | mutated later to register new mappings. 39 | 40 | Examples 41 | -------- 42 | 43 | For untyped scalars: 44 | 45 | .. code-block:: python 46 | 47 | openType = OpenType( 48 | 'id', {1: Integer(), 49 | 2: OctetString()} 50 | ) 51 | Sequence( 52 | componentType=NamedTypes( 53 | NamedType('id', Integer()), 54 | NamedType('blob', Any(), openType=openType) 55 | ) 56 | ) 57 | 58 | For untyped `SET OF` or `SEQUENCE OF` vectors: 59 | 60 | .. code-block:: python 61 | 62 | openType = OpenType( 63 | 'id', {1: Integer(), 64 | 2: OctetString()} 65 | ) 66 | Sequence( 67 | componentType=NamedTypes( 68 | NamedType('id', Integer()), 69 | NamedType('blob', SetOf(componentType=Any()), 70 | openType=openType) 71 | ) 72 | ) 73 | """ 74 | 75 | def __init__(self, name, typeMap=None): 76 | self.__name = name 77 | if typeMap is None: 78 | self.__typeMap = {} 79 | else: 80 | self.__typeMap = typeMap 81 | 82 | @property 83 | def name(self): 84 | return self.__name 85 | 86 | # Python dict protocol 87 | 88 | def values(self): 89 | return self.__typeMap.values() 90 | 91 | def keys(self): 92 | return self.__typeMap.keys() 93 | 94 | def items(self): 95 | return self.__typeMap.items() 96 | 97 | def __contains__(self, key): 98 | return key in self.__typeMap 99 | 100 | def __getitem__(self, key): 101 | return self.__typeMap[key] 102 | 103 | def __iter__(self): 104 | return iter(self.__typeMap) 105 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/type/tag.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | from pyasn1 import error 8 | 9 | __all__ = ['tagClassUniversal', 'tagClassApplication', 'tagClassContext', 10 | 'tagClassPrivate', 'tagFormatSimple', 'tagFormatConstructed', 11 | 'tagCategoryImplicit', 'tagCategoryExplicit', 12 | 'tagCategoryUntagged', 'Tag', 'TagSet'] 13 | 14 | #: Identifier for ASN.1 class UNIVERSAL 15 | tagClassUniversal = 0x00 16 | 17 | #: Identifier for ASN.1 class APPLICATION 18 | tagClassApplication = 0x40 19 | 20 | #: Identifier for ASN.1 class context-specific 21 | tagClassContext = 0x80 22 | 23 | #: Identifier for ASN.1 class private 24 | tagClassPrivate = 0xC0 25 | 26 | #: Identifier for "simple" ASN.1 structure (e.g. scalar) 27 | tagFormatSimple = 0x00 28 | 29 | #: Identifier for "constructed" ASN.1 structure (e.g. may have inner components) 30 | tagFormatConstructed = 0x20 31 | 32 | tagCategoryImplicit = 0x01 33 | tagCategoryExplicit = 0x02 34 | tagCategoryUntagged = 0x04 35 | 36 | 37 | class Tag(object): 38 | """Create ASN.1 tag 39 | 40 | Represents ASN.1 tag that can be attached to a ASN.1 type to make 41 | types distinguishable from each other. 42 | 43 | *Tag* objects are immutable and duck-type Python :class:`tuple` objects 44 | holding three integer components of a tag. 45 | 46 | Parameters 47 | ---------- 48 | tagClass: :py:class:`int` 49 | Tag *class* value 50 | 51 | tagFormat: :py:class:`int` 52 | Tag *format* value 53 | 54 | tagId: :py:class:`int` 55 | Tag ID value 56 | """ 57 | def __init__(self, tagClass, tagFormat, tagId): 58 | if tagId < 0: 59 | raise error.PyAsn1Error('Negative tag ID (%s) not allowed' % tagId) 60 | self.__tagClass = tagClass 61 | self.__tagFormat = tagFormat 62 | self.__tagId = tagId 63 | self.__tagClassId = tagClass, tagId 64 | self.__hash = hash(self.__tagClassId) 65 | 66 | def __repr__(self): 67 | representation = '[%s:%s:%s]' % ( 68 | self.__tagClass, self.__tagFormat, self.__tagId) 69 | return '<%s object, tag %s>' % ( 70 | self.__class__.__name__, representation) 71 | 72 | def __eq__(self, other): 73 | return self.__tagClassId == other 74 | 75 | def __ne__(self, other): 76 | return self.__tagClassId != other 77 | 78 | def __lt__(self, other): 79 | return self.__tagClassId < other 80 | 81 | def __le__(self, other): 82 | return self.__tagClassId <= other 83 | 84 | def __gt__(self, other): 85 | return self.__tagClassId > other 86 | 87 | def __ge__(self, other): 88 | return self.__tagClassId >= other 89 | 90 | def __hash__(self): 91 | return self.__hash 92 | 93 | def __getitem__(self, idx): 94 | if idx == 0: 95 | return self.__tagClass 96 | elif idx == 1: 97 | return self.__tagFormat 98 | elif idx == 2: 99 | return self.__tagId 100 | else: 101 | raise IndexError() 102 | 103 | def __iter__(self): 104 | yield self.__tagClass 105 | yield self.__tagFormat 106 | yield self.__tagId 107 | 108 | def __and__(self, otherTag): 109 | return self.__class__(self.__tagClass & otherTag.tagClass, 110 | self.__tagFormat & otherTag.tagFormat, 111 | self.__tagId & otherTag.tagId) 112 | 113 | def __or__(self, otherTag): 114 | return self.__class__(self.__tagClass | otherTag.tagClass, 115 | self.__tagFormat | otherTag.tagFormat, 116 | self.__tagId | otherTag.tagId) 117 | 118 | @property 119 | def tagClass(self): 120 | """ASN.1 tag class 121 | 122 | Returns 123 | ------- 124 | : :py:class:`int` 125 | Tag class 126 | """ 127 | return self.__tagClass 128 | 129 | @property 130 | def tagFormat(self): 131 | """ASN.1 tag format 132 | 133 | Returns 134 | ------- 135 | : :py:class:`int` 136 | Tag format 137 | """ 138 | return self.__tagFormat 139 | 140 | @property 141 | def tagId(self): 142 | """ASN.1 tag ID 143 | 144 | Returns 145 | ------- 146 | : :py:class:`int` 147 | Tag ID 148 | """ 149 | return self.__tagId 150 | 151 | 152 | class TagSet(object): 153 | """Create a collection of ASN.1 tags 154 | 155 | Represents a combination of :class:`~pyasn1.type.tag.Tag` objects 156 | that can be attached to a ASN.1 type to make types distinguishable 157 | from each other. 158 | 159 | *TagSet* objects are immutable and duck-type Python :class:`tuple` objects 160 | holding arbitrary number of :class:`~pyasn1.type.tag.Tag` objects. 161 | 162 | Parameters 163 | ---------- 164 | baseTag: :class:`~pyasn1.type.tag.Tag` 165 | Base *Tag* object. This tag survives IMPLICIT tagging. 166 | 167 | *superTags: :class:`~pyasn1.type.tag.Tag` 168 | Additional *Tag* objects taking part in subtyping. 169 | 170 | Examples 171 | -------- 172 | .. code-block:: python 173 | 174 | class OrderNumber(NumericString): 175 | ''' 176 | ASN.1 specification 177 | 178 | Order-number ::= 179 | [APPLICATION 5] IMPLICIT NumericString 180 | ''' 181 | tagSet = NumericString.tagSet.tagImplicitly( 182 | Tag(tagClassApplication, tagFormatSimple, 5) 183 | ) 184 | 185 | orderNumber = OrderNumber('1234') 186 | """ 187 | def __init__(self, baseTag=(), *superTags): 188 | self.__baseTag = baseTag 189 | self.__superTags = superTags 190 | self.__superTagsClassId = tuple( 191 | [(superTag.tagClass, superTag.tagId) for superTag in superTags] 192 | ) 193 | self.__lenOfSuperTags = len(superTags) 194 | self.__hash = hash(self.__superTagsClassId) 195 | 196 | def __repr__(self): 197 | representation = '-'.join(['%s:%s:%s' % (x.tagClass, x.tagFormat, x.tagId) 198 | for x in self.__superTags]) 199 | if representation: 200 | representation = 'tags ' + representation 201 | else: 202 | representation = 'untagged' 203 | 204 | return '<%s object, %s>' % (self.__class__.__name__, representation) 205 | 206 | def __add__(self, superTag): 207 | return self.__class__(self.__baseTag, *self.__superTags + (superTag,)) 208 | 209 | def __radd__(self, superTag): 210 | return self.__class__(self.__baseTag, *(superTag,) + self.__superTags) 211 | 212 | def __getitem__(self, i): 213 | if i.__class__ is slice: 214 | return self.__class__(self.__baseTag, *self.__superTags[i]) 215 | else: 216 | return self.__superTags[i] 217 | 218 | def __eq__(self, other): 219 | return self.__superTagsClassId == other 220 | 221 | def __ne__(self, other): 222 | return self.__superTagsClassId != other 223 | 224 | def __lt__(self, other): 225 | return self.__superTagsClassId < other 226 | 227 | def __le__(self, other): 228 | return self.__superTagsClassId <= other 229 | 230 | def __gt__(self, other): 231 | return self.__superTagsClassId > other 232 | 233 | def __ge__(self, other): 234 | return self.__superTagsClassId >= other 235 | 236 | def __hash__(self): 237 | return self.__hash 238 | 239 | def __len__(self): 240 | return self.__lenOfSuperTags 241 | 242 | @property 243 | def baseTag(self): 244 | """Return base ASN.1 tag 245 | 246 | Returns 247 | ------- 248 | : :class:`~pyasn1.type.tag.Tag` 249 | Base tag of this *TagSet* 250 | """ 251 | return self.__baseTag 252 | 253 | @property 254 | def superTags(self): 255 | """Return ASN.1 tags 256 | 257 | Returns 258 | ------- 259 | : :py:class:`tuple` 260 | Tuple of :class:`~pyasn1.type.tag.Tag` objects that this *TagSet* contains 261 | """ 262 | return self.__superTags 263 | 264 | def tagExplicitly(self, superTag): 265 | """Return explicitly tagged *TagSet* 266 | 267 | Create a new *TagSet* representing callee *TagSet* explicitly tagged 268 | with passed tag(s). With explicit tagging mode, new tags are appended 269 | to existing tag(s). 270 | 271 | Parameters 272 | ---------- 273 | superTag: :class:`~pyasn1.type.tag.Tag` 274 | *Tag* object to tag this *TagSet* 275 | 276 | Returns 277 | ------- 278 | : :class:`~pyasn1.type.tag.TagSet` 279 | New *TagSet* object 280 | """ 281 | if superTag.tagClass == tagClassUniversal: 282 | raise error.PyAsn1Error("Can't tag with UNIVERSAL class tag") 283 | if superTag.tagFormat != tagFormatConstructed: 284 | superTag = Tag(superTag.tagClass, tagFormatConstructed, superTag.tagId) 285 | return self + superTag 286 | 287 | def tagImplicitly(self, superTag): 288 | """Return implicitly tagged *TagSet* 289 | 290 | Create a new *TagSet* representing callee *TagSet* implicitly tagged 291 | with passed tag(s). With implicit tagging mode, new tag(s) replace the 292 | last existing tag. 293 | 294 | Parameters 295 | ---------- 296 | superTag: :class:`~pyasn1.type.tag.Tag` 297 | *Tag* object to tag this *TagSet* 298 | 299 | Returns 300 | ------- 301 | : :class:`~pyasn1.type.tag.TagSet` 302 | New *TagSet* object 303 | """ 304 | if self.__superTags: 305 | superTag = Tag(superTag.tagClass, self.__superTags[-1].tagFormat, superTag.tagId) 306 | return self[:-1] + superTag 307 | 308 | def isSuperTagSetOf(self, tagSet): 309 | """Test type relationship against given *TagSet* 310 | 311 | The callee is considered to be a supertype of given *TagSet* 312 | tag-wise if all tags in *TagSet* are present in the callee and 313 | they are in the same order. 314 | 315 | Parameters 316 | ---------- 317 | tagSet: :class:`~pyasn1.type.tag.TagSet` 318 | *TagSet* object to evaluate against the callee 319 | 320 | Returns 321 | ------- 322 | : :py:class:`bool` 323 | :obj:`True` if callee is a supertype of *tagSet* 324 | """ 325 | if len(tagSet) < self.__lenOfSuperTags: 326 | return False 327 | return self.__superTags == tagSet[:self.__lenOfSuperTags] 328 | 329 | # Backward compatibility 330 | 331 | def getBaseTag(self): 332 | return self.__baseTag 333 | 334 | def initTagSet(tag): 335 | return TagSet(tag, tag) 336 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/type/tagmap.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | from pyasn1 import error 8 | 9 | __all__ = ['TagMap'] 10 | 11 | 12 | class TagMap(object): 13 | """Map *TagSet* objects to ASN.1 types 14 | 15 | Create an object mapping *TagSet* object to ASN.1 type. 16 | 17 | *TagMap* objects are immutable and duck-type read-only Python 18 | :class:`dict` objects holding *TagSet* objects as keys and ASN.1 19 | type objects as values. 20 | 21 | Parameters 22 | ---------- 23 | presentTypes: :py:class:`dict` 24 | Map of :class:`~pyasn1.type.tag.TagSet` to ASN.1 objects considered 25 | as being unconditionally present in the *TagMap*. 26 | 27 | skipTypes: :py:class:`dict` 28 | A collection of :class:`~pyasn1.type.tag.TagSet` objects considered 29 | as absent in the *TagMap* even when *defaultType* is present. 30 | 31 | defaultType: ASN.1 type object 32 | An ASN.1 type object callee *TagMap* returns for any *TagSet* key not present 33 | in *presentTypes* (unless given key is present in *skipTypes*). 34 | """ 35 | def __init__(self, presentTypes=None, skipTypes=None, defaultType=None): 36 | self.__presentTypes = presentTypes or {} 37 | self.__skipTypes = skipTypes or {} 38 | self.__defaultType = defaultType 39 | 40 | def __contains__(self, tagSet): 41 | return (tagSet in self.__presentTypes or 42 | self.__defaultType is not None and tagSet not in self.__skipTypes) 43 | 44 | def __getitem__(self, tagSet): 45 | try: 46 | return self.__presentTypes[tagSet] 47 | except KeyError: 48 | if self.__defaultType is None: 49 | raise KeyError() 50 | elif tagSet in self.__skipTypes: 51 | raise error.PyAsn1Error('Key in negative map') 52 | else: 53 | return self.__defaultType 54 | 55 | def __iter__(self): 56 | return iter(self.__presentTypes) 57 | 58 | def __repr__(self): 59 | representation = '%s object' % self.__class__.__name__ 60 | 61 | if self.__presentTypes: 62 | representation += ', present %s' % repr(self.__presentTypes) 63 | 64 | if self.__skipTypes: 65 | representation += ', skip %s' % repr(self.__skipTypes) 66 | 67 | if self.__defaultType is not None: 68 | representation += ', default %s' % repr(self.__defaultType) 69 | 70 | return '<%s>' % representation 71 | 72 | @property 73 | def presentTypes(self): 74 | """Return *TagSet* to ASN.1 type map present in callee *TagMap*""" 75 | return self.__presentTypes 76 | 77 | @property 78 | def skipTypes(self): 79 | """Return *TagSet* collection unconditionally absent in callee *TagMap*""" 80 | return self.__skipTypes 81 | 82 | @property 83 | def defaultType(self): 84 | """Return default ASN.1 type being returned for any missing *TagSet*""" 85 | return self.__defaultType 86 | 87 | # Backward compatibility 88 | 89 | def getPosMap(self): 90 | return self.presentTypes 91 | 92 | def getNegMap(self): 93 | return self.skipTypes 94 | 95 | def getDef(self): 96 | return self.defaultType 97 | -------------------------------------------------------------------------------- /天翼云盘签到/pyasn1/type/useful.py: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of pyasn1 software. 3 | # 4 | # Copyright (c) 2005-2019, Ilya Etingof 5 | # License: http://snmplabs.com/pyasn1/license.html 6 | # 7 | import datetime 8 | 9 | from pyasn1 import error 10 | from pyasn1.compat import dateandtime 11 | from pyasn1.compat import string 12 | from pyasn1.type import char 13 | from pyasn1.type import tag 14 | from pyasn1.type import univ 15 | 16 | __all__ = ['ObjectDescriptor', 'GeneralizedTime', 'UTCTime'] 17 | 18 | NoValue = univ.NoValue 19 | noValue = univ.noValue 20 | 21 | 22 | class ObjectDescriptor(char.GraphicString): 23 | __doc__ = char.GraphicString.__doc__ 24 | 25 | #: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects 26 | tagSet = char.GraphicString.tagSet.tagImplicitly( 27 | tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 7) 28 | ) 29 | 30 | # Optimization for faster codec lookup 31 | typeId = char.GraphicString.getTypeId() 32 | 33 | 34 | class TimeMixIn(object): 35 | 36 | _yearsDigits = 4 37 | _hasSubsecond = False 38 | _optionalMinutes = False 39 | _shortTZ = False 40 | 41 | class FixedOffset(datetime.tzinfo): 42 | """Fixed offset in minutes east from UTC.""" 43 | 44 | # defaulted arguments required 45 | # https: // docs.python.org / 2.3 / lib / datetime - tzinfo.html 46 | def __init__(self, offset=0, name='UTC'): 47 | self.__offset = datetime.timedelta(minutes=offset) 48 | self.__name = name 49 | 50 | def utcoffset(self, dt): 51 | return self.__offset 52 | 53 | def tzname(self, dt): 54 | return self.__name 55 | 56 | def dst(self, dt): 57 | return datetime.timedelta(0) 58 | 59 | UTC = FixedOffset() 60 | 61 | @property 62 | def asDateTime(self): 63 | """Create :py:class:`datetime.datetime` object from a |ASN.1| object. 64 | 65 | Returns 66 | ------- 67 | : 68 | new instance of :py:class:`datetime.datetime` object 69 | """ 70 | text = str(self) 71 | if text.endswith('Z'): 72 | tzinfo = TimeMixIn.UTC 73 | text = text[:-1] 74 | 75 | elif '-' in text or '+' in text: 76 | if '+' in text: 77 | text, plusminus, tz = string.partition(text, '+') 78 | else: 79 | text, plusminus, tz = string.partition(text, '-') 80 | 81 | if self._shortTZ and len(tz) == 2: 82 | tz += '00' 83 | 84 | if len(tz) != 4: 85 | raise error.PyAsn1Error('malformed time zone offset %s' % tz) 86 | 87 | try: 88 | minutes = int(tz[:2]) * 60 + int(tz[2:]) 89 | if plusminus == '-': 90 | minutes *= -1 91 | 92 | except ValueError: 93 | raise error.PyAsn1Error('unknown time specification %s' % self) 94 | 95 | tzinfo = TimeMixIn.FixedOffset(minutes, '?') 96 | 97 | else: 98 | tzinfo = None 99 | 100 | if '.' in text or ',' in text: 101 | if '.' in text: 102 | text, _, ms = string.partition(text, '.') 103 | else: 104 | text, _, ms = string.partition(text, ',') 105 | 106 | try: 107 | ms = int(ms) * 1000 108 | 109 | except ValueError: 110 | raise error.PyAsn1Error('bad sub-second time specification %s' % self) 111 | 112 | else: 113 | ms = 0 114 | 115 | if self._optionalMinutes and len(text) - self._yearsDigits == 6: 116 | text += '0000' 117 | elif len(text) - self._yearsDigits == 8: 118 | text += '00' 119 | 120 | try: 121 | dt = dateandtime.strptime(text, self._yearsDigits == 4 and '%Y%m%d%H%M%S' or '%y%m%d%H%M%S') 122 | 123 | except ValueError: 124 | raise error.PyAsn1Error('malformed datetime format %s' % self) 125 | 126 | return dt.replace(microsecond=ms, tzinfo=tzinfo) 127 | 128 | @classmethod 129 | def fromDateTime(cls, dt): 130 | """Create |ASN.1| object from a :py:class:`datetime.datetime` object. 131 | 132 | Parameters 133 | ---------- 134 | dt: :py:class:`datetime.datetime` object 135 | The `datetime.datetime` object to initialize the |ASN.1| object 136 | from 137 | 138 | Returns 139 | ------- 140 | : 141 | new instance of |ASN.1| value 142 | """ 143 | text = dt.strftime(cls._yearsDigits == 4 and '%Y%m%d%H%M%S' or '%y%m%d%H%M%S') 144 | if cls._hasSubsecond: 145 | text += '.%d' % (dt.microsecond // 1000) 146 | 147 | if dt.utcoffset(): 148 | seconds = dt.utcoffset().seconds 149 | if seconds < 0: 150 | text += '-' 151 | else: 152 | text += '+' 153 | text += '%.2d%.2d' % (seconds // 3600, seconds % 3600) 154 | else: 155 | text += 'Z' 156 | 157 | return cls(text) 158 | 159 | 160 | class GeneralizedTime(char.VisibleString, TimeMixIn): 161 | __doc__ = char.VisibleString.__doc__ 162 | 163 | #: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects 164 | tagSet = char.VisibleString.tagSet.tagImplicitly( 165 | tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 24) 166 | ) 167 | 168 | # Optimization for faster codec lookup 169 | typeId = char.VideotexString.getTypeId() 170 | 171 | _yearsDigits = 4 172 | _hasSubsecond = True 173 | _optionalMinutes = True 174 | _shortTZ = True 175 | 176 | 177 | class UTCTime(char.VisibleString, TimeMixIn): 178 | __doc__ = char.VisibleString.__doc__ 179 | 180 | #: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects 181 | tagSet = char.VisibleString.tagSet.tagImplicitly( 182 | tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 23) 183 | ) 184 | 185 | # Optimization for faster codec lookup 186 | typeId = char.VideotexString.getTypeId() 187 | 188 | _yearsDigits = 2 189 | _hasSubsecond = False 190 | _optionalMinutes = False 191 | _shortTZ = False 192 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa-4.6.dist-info/INSTALLER: -------------------------------------------------------------------------------- 1 | pip 2 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa-4.6.dist-info/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2011 Sybren A. Stüvel 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | https://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa-4.6.dist-info/METADATA: -------------------------------------------------------------------------------- 1 | Metadata-Version: 2.1 2 | Name: rsa 3 | Version: 4.6 4 | Summary: Pure-Python RSA implementation 5 | Home-page: https://stuvel.eu/rsa 6 | Author: Sybren A. Stuvel 7 | Author-email: sybren@stuvel.eu 8 | Maintainer: Sybren A. Stuvel 9 | Maintainer-email: sybren@stuvel.eu 10 | License: ASL 2 11 | Platform: UNKNOWN 12 | Classifier: Development Status :: 5 - Production/Stable 13 | Classifier: Intended Audience :: Developers 14 | Classifier: Intended Audience :: Education 15 | Classifier: Intended Audience :: Information Technology 16 | Classifier: License :: OSI Approved :: Apache Software License 17 | Classifier: Operating System :: OS Independent 18 | Classifier: Programming Language :: Python 19 | Classifier: Programming Language :: Python :: 3 20 | Classifier: Programming Language :: Python :: 3.5 21 | Classifier: Programming Language :: Python :: 3.6 22 | Classifier: Programming Language :: Python :: 3.7 23 | Classifier: Programming Language :: Python :: 3.8 24 | Classifier: Programming Language :: Python :: Implementation :: CPython 25 | Classifier: Programming Language :: Python :: Implementation :: PyPy 26 | Classifier: Topic :: Security :: Cryptography 27 | Requires-Python: >=3.5, <4 28 | Description-Content-Type: text/markdown 29 | Requires-Dist: pyasn1 (>=0.1.3) 30 | 31 | Pure Python RSA implementation 32 | ============================== 33 | 34 | [![PyPI](https://img.shields.io/pypi/v/rsa.svg)](https://pypi.org/project/rsa/) 35 | [![Build Status](https://travis-ci.org/sybrenstuvel/python-rsa.svg?branch=master)](https://travis-ci.org/sybrenstuvel/python-rsa) 36 | [![Coverage Status](https://coveralls.io/repos/github/sybrenstuvel/python-rsa/badge.svg?branch=master)](https://coveralls.io/github/sybrenstuvel/python-rsa?branch=master) 37 | [![Code Climate](https://api.codeclimate.com/v1/badges/a99a88d28ad37a79dbf6/maintainability)](https://codeclimate.com/github/codeclimate/codeclimate/maintainability) 38 | 39 | [Python-RSA](https://stuvel.eu/rsa) is a pure-Python RSA implementation. It supports 40 | encryption and decryption, signing and verifying signatures, and key 41 | generation according to PKCS#1 version 1.5. It can be used as a Python 42 | library as well as on the commandline. The code was mostly written by 43 | Sybren A. Stüvel. 44 | 45 | Documentation can be found at the [Python-RSA homepage](https://stuvel.eu/rsa). For all changes, check [the changelog](https://github.com/sybrenstuvel/python-rsa/blob/master/CHANGELOG.md). 46 | 47 | Download and install using: 48 | 49 | pip install rsa 50 | 51 | or download it from the [Python Package Index](https://pypi.org/project/rsa/). 52 | 53 | The source code is maintained at [GitHub](https://github.com/sybrenstuvel/python-rsa/) and is 54 | licensed under the [Apache License, version 2.0](https://www.apache.org/licenses/LICENSE-2.0) 55 | 56 | Major changes in 4.1 57 | -------------------- 58 | 59 | Version 4.0 was the last version to support Python 2 and 3.4. Version 4.1 is compatible with Python 3.5+ only. 60 | 61 | 62 | Major changes in 4.0 63 | -------------------- 64 | 65 | Version 3.4 was the last version in the 3.x range. Version 4.0 drops the following modules, 66 | as they are insecure: 67 | 68 | - `rsa._version133` 69 | - `rsa._version200` 70 | - `rsa.bigfile` 71 | - `rsa.varblock` 72 | 73 | Those modules were marked as deprecated in version 3.4. 74 | 75 | Furthermore, in 4.0 the I/O functions is streamlined to always work with bytes on all 76 | supported versions of Python. 77 | 78 | Version 4.0 drops support for Python 2.6 and 3.3. 79 | 80 | 81 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa-4.6.dist-info/RECORD: -------------------------------------------------------------------------------- 1 | ../../bin/pyrsa-decrypt,sha256=YA-GYQRWhytrvG-53EjLZkB65QKqEF3yTFrOWFKWj48,225 2 | ../../bin/pyrsa-encrypt,sha256=c9_aFCyMNSdUnwMl7gAHl-FfLRmg5G0hWWE2_zd0CzY,225 3 | ../../bin/pyrsa-keygen,sha256=0cNsuLPlJsYm8ewAKFfIN8r3Efzmq_PEgXb5INhuFls,223 4 | ../../bin/pyrsa-priv2pub,sha256=NCLCg8mLUmM6OAjBE3W-iBUl6mDZLpRIOaVgSPe_aRU,246 5 | ../../bin/pyrsa-sign,sha256=AkE1DDZax5ztsjXEhrjVmZqkJTWoLM2tcpdlqsz-rAA,219 6 | ../../bin/pyrsa-verify,sha256=Cemjt2bP12mmVHwVvIEuwmYAXt0vVC9t4GXw9QQYzuk,223 7 | rsa-4.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 8 | rsa-4.6.dist-info/LICENSE,sha256=Bz8ot9OJyP509gfhfCf4HqpazmntxDqITyP0G0HFxyY,577 9 | rsa-4.6.dist-info/METADATA,sha256=tF-qq6z4RpPWUg9pd050KMYgZFIhwyQQXQXkRQTSwkk,3208 10 | rsa-4.6.dist-info/RECORD,, 11 | rsa-4.6.dist-info/WHEEL,sha256=g4nMs7d-Xl9-xC9XovUrsDHGXt-FT0E17Yqo92DEfvY,92 12 | rsa-4.6.dist-info/entry_points.txt,sha256=CfbS6zx6jc_obqg6SQDd9J0QdoGYDMKFosDQ9ADn_Pg,213 13 | rsa-4.6.dist-info/top_level.txt,sha256=fAq1Bm-GX3Blvuu7bvG87v7ye2ZJoIL7oVz1F9FdxjI,4 14 | rsa/__init__.py,sha256=h9BVqRruSvO_4QmcPs2dujtGJbSM5wQ7QRWwrSzczMY,1542 15 | rsa/__pycache__/__init__.cpython-36.pyc,, 16 | rsa/__pycache__/_compat.cpython-36.pyc,, 17 | rsa/__pycache__/_version133.cpython-36.pyc,, 18 | rsa/__pycache__/_version200.cpython-36.pyc,, 19 | rsa/__pycache__/asn1.cpython-36.pyc,, 20 | rsa/__pycache__/bigfile.cpython-36.pyc,, 21 | rsa/__pycache__/cli.cpython-36.pyc,, 22 | rsa/__pycache__/common.cpython-36.pyc,, 23 | rsa/__pycache__/core.cpython-36.pyc,, 24 | rsa/__pycache__/key.cpython-36.pyc,, 25 | rsa/__pycache__/parallel.cpython-36.pyc,, 26 | rsa/__pycache__/pem.cpython-36.pyc,, 27 | rsa/__pycache__/pkcs1.cpython-36.pyc,, 28 | rsa/__pycache__/pkcs1_v2.cpython-36.pyc,, 29 | rsa/__pycache__/prime.cpython-36.pyc,, 30 | rsa/__pycache__/randnum.cpython-36.pyc,, 31 | rsa/__pycache__/transform.cpython-36.pyc,, 32 | rsa/__pycache__/util.cpython-36.pyc,, 33 | rsa/__pycache__/varblock.cpython-36.pyc,, 34 | rsa/_compat.py,sha256=TxeP2UMfzzBLIonvsOAJeUjGUss5Jqzxf_OBZ_-U55U,1486 35 | rsa/_version133.py,sha256=wo9MgBf3oURMyTkAQ9v1heQcVYTp4H3yty1S54BrWHM,11764 36 | rsa/_version200.py,sha256=dlTSjymiQaBCU5CwOreLY3-oefLAiuMh7b6fDHRFRls,15123 37 | rsa/asn1.py,sha256=PATmCQA8q4ACEQthh7PQJ_eBSM-hd9kJe8AvgcBSVk8,1755 38 | rsa/bigfile.py,sha256=NaRpXpN0oCLef6YUL0xjDX1Rt75HNh8WWmmyu6Sdhgk,5185 39 | rsa/cli.py,sha256=5XlXri_r9KB42M434UPs_Zr07ara2Reko2lGSlD7KPs,9971 40 | rsa/common.py,sha256=9L71g02m_KjZL1uE5zxJBADjoHXqp7i9Uj1z9cI7TMs,4668 41 | rsa/core.py,sha256=jdLgt5PKLgwxlzJTtcQf-pFoaOVBuTkW-Qbe6yI-ZZk,1661 42 | rsa/key.py,sha256=vNtqa3ULkON5z37vIKtErQZZrHhO0wkF8V7vObLQIy4,25691 43 | rsa/parallel.py,sha256=BWa9xCqj90CmjUsVSFcZ6cDGNeF5BVUWBj3lWmQYJYs,2326 44 | rsa/pem.py,sha256=9B4KYI7aPAayCbXOAeDz4flWJouaf8Io9_dItJbwN7k,3976 45 | rsa/pkcs1.py,sha256=pscFllSrnFwlSZpJt8jc2teKiSfLejrGtm8CnJGbCNk,15515 46 | rsa/pkcs1_v2.py,sha256=WlA9vbvyjpHYmK7sra3Rvk-ZDxoPk88FYH9gDgH1OII,3433 47 | rsa/prime.py,sha256=Ba6twrpKQofhczYORy08HXj02J-6pOSg1esiNQYwctM,5105 48 | rsa/randnum.py,sha256=5w2v2i3uUYT7lPksY__L6GODflVoFAgCqVLZTM7Mu8I,2664 49 | rsa/transform.py,sha256=OA26lxSlY5VmQwQc7g8IMuu8WE5VVQp8FLQ2NCMp-wQ,2200 50 | rsa/util.py,sha256=REoqdewjl0_pzxO6RJrZt8haVMeZbtq3bckpWLwFMcw,2986 51 | rsa/varblock.py,sha256=v8c3ST2uF58CDCcJq_wdxccjqAiGM_A4T6TIAr5uMZI,5406 52 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa-4.6.dist-info/WHEEL: -------------------------------------------------------------------------------- 1 | Wheel-Version: 1.0 2 | Generator: bdist_wheel (0.34.2) 3 | Root-Is-Purelib: true 4 | Tag: py3-none-any 5 | 6 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa-4.6.dist-info/entry_points.txt: -------------------------------------------------------------------------------- 1 | [console_scripts] 2 | pyrsa-decrypt = rsa.cli:decrypt 3 | pyrsa-encrypt = rsa.cli:encrypt 4 | pyrsa-keygen = rsa.cli:keygen 5 | pyrsa-priv2pub = rsa.util:private_to_public 6 | pyrsa-sign = rsa.cli:sign 7 | pyrsa-verify = rsa.cli:verify 8 | 9 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa-4.6.dist-info/top_level.txt: -------------------------------------------------------------------------------- 1 | rsa 2 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Sybren A. Stüvel 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | """RSA module 15 | 16 | Module for calculating large primes, and RSA encryption, decryption, signing 17 | and verification. Includes generating public and private keys. 18 | 19 | WARNING: this implementation does not use compression of the cleartext input to 20 | prevent repetitions, or other common security improvements. Use with care. 21 | 22 | """ 23 | 24 | from rsa.key import newkeys, PrivateKey, PublicKey 25 | from rsa.pkcs1 import encrypt, decrypt, sign, verify, DecryptionError, \ 26 | VerificationError, find_signature_hash, sign_hash, compute_hash 27 | 28 | __author__ = "Sybren Stuvel, Barry Mead and Yesudeep Mangalapilly" 29 | __date__ = '2020-06-12' 30 | __version__ = '4.6' 31 | 32 | # Do doctest if we're run directly 33 | if __name__ == "__main__": 34 | import doctest 35 | 36 | doctest.testmod() 37 | 38 | __all__ = ["newkeys", "encrypt", "decrypt", "sign", "verify", 'PublicKey', 39 | 'PrivateKey', 'DecryptionError', 'VerificationError', 40 | 'find_signature_hash', 'compute_hash', 'sign_hash'] 41 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa/_compat.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Sybren A. Stüvel 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Python compatibility wrappers.""" 16 | 17 | from struct import pack 18 | 19 | 20 | def byte(num: int) -> bytes: 21 | """ 22 | Converts a number between 0 and 255 (both inclusive) to a base-256 (byte) 23 | representation. 24 | 25 | :param num: 26 | An unsigned integer between 0 and 255 (both inclusive). 27 | :returns: 28 | A single byte. 29 | """ 30 | return pack("B", num) 31 | 32 | 33 | def xor_bytes(b1: bytes, b2: bytes) -> bytes: 34 | """ 35 | Returns the bitwise XOR result between two bytes objects, b1 ^ b2. 36 | 37 | Bitwise XOR operation is commutative, so order of parameters doesn't 38 | generate different results. If parameters have different length, extra 39 | length of the largest one is ignored. 40 | 41 | :param b1: 42 | First bytes object. 43 | :param b2: 44 | Second bytes object. 45 | :returns: 46 | Bytes object, result of XOR operation. 47 | """ 48 | return bytes(x ^ y for x, y in zip(b1, b2)) 49 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa/asn1.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Sybren A. Stüvel 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ASN.1 definitions. 16 | 17 | Not all ASN.1-handling code use these definitions, but when it does, they should be here. 18 | """ 19 | 20 | from pyasn1.type import univ, namedtype, tag 21 | 22 | 23 | class PubKeyHeader(univ.Sequence): 24 | componentType = namedtype.NamedTypes( 25 | namedtype.NamedType('oid', univ.ObjectIdentifier()), 26 | namedtype.NamedType('parameters', univ.Null()), 27 | ) 28 | 29 | 30 | class OpenSSLPubKey(univ.Sequence): 31 | componentType = namedtype.NamedTypes( 32 | namedtype.NamedType('header', PubKeyHeader()), 33 | 34 | # This little hack (the implicit tag) allows us to get a Bit String as Octet String 35 | namedtype.NamedType('key', univ.OctetString().subtype( 36 | implicitTag=tag.Tag(tagClass=0, tagFormat=0, tagId=3))), 37 | ) 38 | 39 | 40 | class AsnPubKey(univ.Sequence): 41 | """ASN.1 contents of DER encoded public key: 42 | 43 | RSAPublicKey ::= SEQUENCE { 44 | modulus INTEGER, -- n 45 | publicExponent INTEGER, -- e 46 | """ 47 | 48 | componentType = namedtype.NamedTypes( 49 | namedtype.NamedType('modulus', univ.Integer()), 50 | namedtype.NamedType('publicExponent', univ.Integer()), 51 | ) 52 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa/bigfile.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright 2011 Sybren A. Stüvel 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """Large file support 18 | 19 | .. deprecated:: 3.4 20 | 21 | The VARBLOCK format is NOT recommended for general use, has been deprecated since 22 | Python-RSA 3.4, and will be removed in a future release. It's vulnerable to a 23 | number of attacks: 24 | 25 | 1. decrypt/encrypt_bigfile() does not implement `Authenticated encryption`_ nor 26 | uses MACs to verify messages before decrypting public key encrypted messages. 27 | 28 | 2. decrypt/encrypt_bigfile() does not use hybrid encryption (it uses plain RSA) 29 | and has no method for chaining, so block reordering is possible. 30 | 31 | See `issue #19 on Github`_ for more information. 32 | 33 | .. _Authenticated encryption: https://en.wikipedia.org/wiki/Authenticated_encryption 34 | .. _issue #19 on Github: https://github.com/sybrenstuvel/python-rsa/issues/13 35 | 36 | 37 | This module contains functions to: 38 | 39 | - break a file into smaller blocks, and encrypt them, and store the 40 | encrypted blocks in another file. 41 | 42 | - take such an encrypted files, decrypt its blocks, and reconstruct the 43 | original file. 44 | 45 | The encrypted file format is as follows, where || denotes byte concatenation: 46 | 47 | FILE := VERSION || BLOCK || BLOCK ... 48 | 49 | BLOCK := LENGTH || DATA 50 | 51 | LENGTH := varint-encoded length of the subsequent data. Varint comes from 52 | Google Protobuf, and encodes an integer into a variable number of bytes. 53 | Each byte uses the 7 lowest bits to encode the value. The highest bit set 54 | to 1 indicates the next byte is also part of the varint. The last byte will 55 | have this bit set to 0. 56 | 57 | This file format is called the VARBLOCK format, in line with the varint format 58 | used to denote the block sizes. 59 | 60 | """ 61 | 62 | import warnings 63 | 64 | from rsa import key, common, pkcs1, varblock 65 | from rsa._compat import byte 66 | 67 | 68 | def encrypt_bigfile(infile, outfile, pub_key): 69 | """Encrypts a file, writing it to 'outfile' in VARBLOCK format. 70 | 71 | .. deprecated:: 3.4 72 | This function was deprecated in Python-RSA version 3.4 due to security issues 73 | in the VARBLOCK format. See the documentation_ for more information. 74 | 75 | .. _documentation: https://stuvel.eu/python-rsa-doc/usage.html#working-with-big-files 76 | 77 | :param infile: file-like object to read the cleartext from 78 | :param outfile: file-like object to write the crypto in VARBLOCK format to 79 | :param pub_key: :py:class:`rsa.PublicKey` to encrypt with 80 | 81 | """ 82 | 83 | warnings.warn("The 'rsa.bigfile.encrypt_bigfile' function was deprecated in Python-RSA version " 84 | "3.4 due to security issues in the VARBLOCK format. See " 85 | "https://stuvel.eu/python-rsa-doc/usage.html#working-with-big-files " 86 | "for more information.", 87 | DeprecationWarning, stacklevel=2) 88 | 89 | if not isinstance(pub_key, key.PublicKey): 90 | raise TypeError('Public key required, but got %r' % pub_key) 91 | 92 | key_bytes = common.bit_size(pub_key.n) // 8 93 | blocksize = key_bytes - 11 # keep space for PKCS#1 padding 94 | 95 | # Write the version number to the VARBLOCK file 96 | outfile.write(byte(varblock.VARBLOCK_VERSION)) 97 | 98 | # Encrypt and write each block 99 | for block in varblock.yield_fixedblocks(infile, blocksize): 100 | crypto = pkcs1.encrypt(block, pub_key) 101 | 102 | varblock.write_varint(outfile, len(crypto)) 103 | outfile.write(crypto) 104 | 105 | 106 | def decrypt_bigfile(infile, outfile, priv_key): 107 | """Decrypts an encrypted VARBLOCK file, writing it to 'outfile' 108 | 109 | .. deprecated:: 3.4 110 | This function was deprecated in Python-RSA version 3.4 due to security issues 111 | in the VARBLOCK format. See the documentation_ for more information. 112 | 113 | .. _documentation: https://stuvel.eu/python-rsa-doc/usage.html#working-with-big-files 114 | 115 | :param infile: file-like object to read the crypto in VARBLOCK format from 116 | :param outfile: file-like object to write the cleartext to 117 | :param priv_key: :py:class:`rsa.PrivateKey` to decrypt with 118 | 119 | """ 120 | 121 | warnings.warn("The 'rsa.bigfile.decrypt_bigfile' function was deprecated in Python-RSA version " 122 | "3.4 due to security issues in the VARBLOCK format. See " 123 | "https://stuvel.eu/python-rsa-doc/usage.html#working-with-big-files " 124 | "for more information.", 125 | DeprecationWarning, stacklevel=2) 126 | 127 | if not isinstance(priv_key, key.PrivateKey): 128 | raise TypeError('Private key required, but got %r' % priv_key) 129 | 130 | for block in varblock.yield_varblocks(infile): 131 | cleartext = pkcs1.decrypt(block, priv_key) 132 | outfile.write(cleartext) 133 | 134 | 135 | __all__ = ['encrypt_bigfile', 'decrypt_bigfile'] 136 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa/cli.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Sybren A. Stüvel 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Commandline scripts. 16 | 17 | These scripts are called by the executables defined in setup.py. 18 | """ 19 | 20 | import abc 21 | import sys 22 | import typing 23 | import optparse 24 | 25 | import rsa 26 | import rsa.key 27 | import rsa.pkcs1 28 | 29 | HASH_METHODS = sorted(rsa.pkcs1.HASH_METHODS.keys()) 30 | Indexable = typing.Union[typing.Tuple, typing.List[str]] 31 | 32 | 33 | def keygen() -> None: 34 | """Key generator.""" 35 | 36 | # Parse the CLI options 37 | parser = optparse.OptionParser(usage='usage: %prog [options] keysize', 38 | description='Generates a new RSA keypair of "keysize" bits.') 39 | 40 | parser.add_option('--pubout', type='string', 41 | help='Output filename for the public key. The public key is ' 42 | 'not saved if this option is not present. You can use ' 43 | 'pyrsa-priv2pub to create the public key file later.') 44 | 45 | parser.add_option('-o', '--out', type='string', 46 | help='Output filename for the private key. The key is ' 47 | 'written to stdout if this option is not present.') 48 | 49 | parser.add_option('--form', 50 | help='key format of the private and public keys - default PEM', 51 | choices=('PEM', 'DER'), default='PEM') 52 | 53 | (cli, cli_args) = parser.parse_args(sys.argv[1:]) 54 | 55 | if len(cli_args) != 1: 56 | parser.print_help() 57 | raise SystemExit(1) 58 | 59 | try: 60 | keysize = int(cli_args[0]) 61 | except ValueError: 62 | parser.print_help() 63 | print('Not a valid number: %s' % cli_args[0], file=sys.stderr) 64 | raise SystemExit(1) 65 | 66 | print('Generating %i-bit key' % keysize, file=sys.stderr) 67 | (pub_key, priv_key) = rsa.newkeys(keysize) 68 | 69 | # Save public key 70 | if cli.pubout: 71 | print('Writing public key to %s' % cli.pubout, file=sys.stderr) 72 | data = pub_key.save_pkcs1(format=cli.form) 73 | with open(cli.pubout, 'wb') as outfile: 74 | outfile.write(data) 75 | 76 | # Save private key 77 | data = priv_key.save_pkcs1(format=cli.form) 78 | 79 | if cli.out: 80 | print('Writing private key to %s' % cli.out, file=sys.stderr) 81 | with open(cli.out, 'wb') as outfile: 82 | outfile.write(data) 83 | else: 84 | print('Writing private key to stdout', file=sys.stderr) 85 | sys.stdout.buffer.write(data) 86 | 87 | 88 | class CryptoOperation(metaclass=abc.ABCMeta): 89 | """CLI callable that operates with input, output, and a key.""" 90 | 91 | keyname = 'public' # or 'private' 92 | usage = 'usage: %%prog [options] %(keyname)s_key' 93 | description = '' 94 | operation = 'decrypt' 95 | operation_past = 'decrypted' 96 | operation_progressive = 'decrypting' 97 | input_help = 'Name of the file to %(operation)s. Reads from stdin if ' \ 98 | 'not specified.' 99 | output_help = 'Name of the file to write the %(operation_past)s file ' \ 100 | 'to. Written to stdout if this option is not present.' 101 | expected_cli_args = 1 102 | has_output = True 103 | 104 | key_class = rsa.PublicKey # type: typing.Type[rsa.key.AbstractKey] 105 | 106 | def __init__(self) -> None: 107 | self.usage = self.usage % self.__class__.__dict__ 108 | self.input_help = self.input_help % self.__class__.__dict__ 109 | self.output_help = self.output_help % self.__class__.__dict__ 110 | 111 | @abc.abstractmethod 112 | def perform_operation(self, indata: bytes, key: rsa.key.AbstractKey, 113 | cli_args: Indexable) -> typing.Any: 114 | """Performs the program's operation. 115 | 116 | Implement in a subclass. 117 | 118 | :returns: the data to write to the output. 119 | """ 120 | 121 | def __call__(self) -> None: 122 | """Runs the program.""" 123 | 124 | (cli, cli_args) = self.parse_cli() 125 | 126 | key = self.read_key(cli_args[0], cli.keyform) 127 | 128 | indata = self.read_infile(cli.input) 129 | 130 | print(self.operation_progressive.title(), file=sys.stderr) 131 | outdata = self.perform_operation(indata, key, cli_args) 132 | 133 | if self.has_output: 134 | self.write_outfile(outdata, cli.output) 135 | 136 | def parse_cli(self) -> typing.Tuple[optparse.Values, typing.List[str]]: 137 | """Parse the CLI options 138 | 139 | :returns: (cli_opts, cli_args) 140 | """ 141 | 142 | parser = optparse.OptionParser(usage=self.usage, description=self.description) 143 | 144 | parser.add_option('-i', '--input', type='string', help=self.input_help) 145 | 146 | if self.has_output: 147 | parser.add_option('-o', '--output', type='string', help=self.output_help) 148 | 149 | parser.add_option('--keyform', 150 | help='Key format of the %s key - default PEM' % self.keyname, 151 | choices=('PEM', 'DER'), default='PEM') 152 | 153 | (cli, cli_args) = parser.parse_args(sys.argv[1:]) 154 | 155 | if len(cli_args) != self.expected_cli_args: 156 | parser.print_help() 157 | raise SystemExit(1) 158 | 159 | return cli, cli_args 160 | 161 | def read_key(self, filename: str, keyform: str) -> rsa.key.AbstractKey: 162 | """Reads a public or private key.""" 163 | 164 | print('Reading %s key from %s' % (self.keyname, filename), file=sys.stderr) 165 | with open(filename, 'rb') as keyfile: 166 | keydata = keyfile.read() 167 | 168 | return self.key_class.load_pkcs1(keydata, keyform) 169 | 170 | def read_infile(self, inname: str) -> bytes: 171 | """Read the input file""" 172 | 173 | if inname: 174 | print('Reading input from %s' % inname, file=sys.stderr) 175 | with open(inname, 'rb') as infile: 176 | return infile.read() 177 | 178 | print('Reading input from stdin', file=sys.stderr) 179 | return sys.stdin.buffer.read() 180 | 181 | def write_outfile(self, outdata: bytes, outname: str) -> None: 182 | """Write the output file""" 183 | 184 | if outname: 185 | print('Writing output to %s' % outname, file=sys.stderr) 186 | with open(outname, 'wb') as outfile: 187 | outfile.write(outdata) 188 | else: 189 | print('Writing output to stdout', file=sys.stderr) 190 | sys.stdout.buffer.write(outdata) 191 | 192 | 193 | class EncryptOperation(CryptoOperation): 194 | """Encrypts a file.""" 195 | 196 | keyname = 'public' 197 | description = ('Encrypts a file. The file must be shorter than the key ' 198 | 'length in order to be encrypted.') 199 | operation = 'encrypt' 200 | operation_past = 'encrypted' 201 | operation_progressive = 'encrypting' 202 | 203 | def perform_operation(self, indata: bytes, pub_key: rsa.key.AbstractKey, 204 | cli_args: Indexable = ()) -> bytes: 205 | """Encrypts files.""" 206 | assert isinstance(pub_key, rsa.key.PublicKey) 207 | return rsa.encrypt(indata, pub_key) 208 | 209 | 210 | class DecryptOperation(CryptoOperation): 211 | """Decrypts a file.""" 212 | 213 | keyname = 'private' 214 | description = ('Decrypts a file. The original file must be shorter than ' 215 | 'the key length in order to have been encrypted.') 216 | operation = 'decrypt' 217 | operation_past = 'decrypted' 218 | operation_progressive = 'decrypting' 219 | key_class = rsa.PrivateKey 220 | 221 | def perform_operation(self, indata: bytes, priv_key: rsa.key.AbstractKey, 222 | cli_args: Indexable = ()) -> bytes: 223 | """Decrypts files.""" 224 | assert isinstance(priv_key, rsa.key.PrivateKey) 225 | return rsa.decrypt(indata, priv_key) 226 | 227 | 228 | class SignOperation(CryptoOperation): 229 | """Signs a file.""" 230 | 231 | keyname = 'private' 232 | usage = 'usage: %%prog [options] private_key hash_method' 233 | description = ('Signs a file, outputs the signature. Choose the hash ' 234 | 'method from %s' % ', '.join(HASH_METHODS)) 235 | operation = 'sign' 236 | operation_past = 'signature' 237 | operation_progressive = 'Signing' 238 | key_class = rsa.PrivateKey 239 | expected_cli_args = 2 240 | 241 | output_help = ('Name of the file to write the signature to. Written ' 242 | 'to stdout if this option is not present.') 243 | 244 | def perform_operation(self, indata: bytes, priv_key: rsa.key.AbstractKey, 245 | cli_args: Indexable) -> bytes: 246 | """Signs files.""" 247 | assert isinstance(priv_key, rsa.key.PrivateKey) 248 | 249 | hash_method = cli_args[1] 250 | if hash_method not in HASH_METHODS: 251 | raise SystemExit('Invalid hash method, choose one of %s' % 252 | ', '.join(HASH_METHODS)) 253 | 254 | return rsa.sign(indata, priv_key, hash_method) 255 | 256 | 257 | class VerifyOperation(CryptoOperation): 258 | """Verify a signature.""" 259 | 260 | keyname = 'public' 261 | usage = 'usage: %%prog [options] public_key signature_file' 262 | description = ('Verifies a signature, exits with status 0 upon success, ' 263 | 'prints an error message and exits with status 1 upon error.') 264 | operation = 'verify' 265 | operation_past = 'verified' 266 | operation_progressive = 'Verifying' 267 | key_class = rsa.PublicKey 268 | expected_cli_args = 2 269 | has_output = False 270 | 271 | def perform_operation(self, indata: bytes, pub_key: rsa.key.AbstractKey, 272 | cli_args: Indexable) -> None: 273 | """Verifies files.""" 274 | assert isinstance(pub_key, rsa.key.PublicKey) 275 | 276 | signature_file = cli_args[1] 277 | 278 | with open(signature_file, 'rb') as sigfile: 279 | signature = sigfile.read() 280 | 281 | try: 282 | rsa.verify(indata, signature, pub_key) 283 | except rsa.VerificationError: 284 | raise SystemExit('Verification failed.') 285 | 286 | print('Verification OK', file=sys.stderr) 287 | 288 | 289 | encrypt = EncryptOperation() 290 | decrypt = DecryptOperation() 291 | sign = SignOperation() 292 | verify = VerifyOperation() 293 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa/common.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Sybren A. Stüvel 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Common functionality shared by several modules.""" 16 | 17 | import typing 18 | 19 | 20 | class NotRelativePrimeError(ValueError): 21 | def __init__(self, a: int, b: int, d: int, msg: str = '') -> None: 22 | super().__init__(msg or "%d and %d are not relatively prime, divider=%i" % (a, b, d)) 23 | self.a = a 24 | self.b = b 25 | self.d = d 26 | 27 | 28 | def bit_size(num: int) -> int: 29 | """ 30 | Number of bits needed to represent a integer excluding any prefix 31 | 0 bits. 32 | 33 | Usage:: 34 | 35 | >>> bit_size(1023) 36 | 10 37 | >>> bit_size(1024) 38 | 11 39 | >>> bit_size(1025) 40 | 11 41 | 42 | :param num: 43 | Integer value. If num is 0, returns 0. Only the absolute value of the 44 | number is considered. Therefore, signed integers will be abs(num) 45 | before the number's bit length is determined. 46 | :returns: 47 | Returns the number of bits in the integer. 48 | """ 49 | 50 | try: 51 | return num.bit_length() 52 | except AttributeError: 53 | raise TypeError('bit_size(num) only supports integers, not %r' % type(num)) 54 | 55 | 56 | def byte_size(number: int) -> int: 57 | """ 58 | Returns the number of bytes required to hold a specific long number. 59 | 60 | The number of bytes is rounded up. 61 | 62 | Usage:: 63 | 64 | >>> byte_size(1 << 1023) 65 | 128 66 | >>> byte_size((1 << 1024) - 1) 67 | 128 68 | >>> byte_size(1 << 1024) 69 | 129 70 | 71 | :param number: 72 | An unsigned integer 73 | :returns: 74 | The number of bytes required to hold a specific long number. 75 | """ 76 | if number == 0: 77 | return 1 78 | return ceil_div(bit_size(number), 8) 79 | 80 | 81 | def ceil_div(num: int, div: int) -> int: 82 | """ 83 | Returns the ceiling function of a division between `num` and `div`. 84 | 85 | Usage:: 86 | 87 | >>> ceil_div(100, 7) 88 | 15 89 | >>> ceil_div(100, 10) 90 | 10 91 | >>> ceil_div(1, 4) 92 | 1 93 | 94 | :param num: Division's numerator, a number 95 | :param div: Division's divisor, a number 96 | 97 | :return: Rounded up result of the division between the parameters. 98 | """ 99 | quanta, mod = divmod(num, div) 100 | if mod: 101 | quanta += 1 102 | return quanta 103 | 104 | 105 | def extended_gcd(a: int, b: int) -> typing.Tuple[int, int, int]: 106 | """Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb 107 | """ 108 | # r = gcd(a,b) i = multiplicitive inverse of a mod b 109 | # or j = multiplicitive inverse of b mod a 110 | # Neg return values for i or j are made positive mod b or a respectively 111 | # Iterateive Version is faster and uses much less stack space 112 | x = 0 113 | y = 1 114 | lx = 1 115 | ly = 0 116 | oa = a # Remember original a/b to remove 117 | ob = b # negative values from return results 118 | while b != 0: 119 | q = a // b 120 | (a, b) = (b, a % b) 121 | (x, lx) = ((lx - (q * x)), x) 122 | (y, ly) = ((ly - (q * y)), y) 123 | if lx < 0: 124 | lx += ob # If neg wrap modulo orignal b 125 | if ly < 0: 126 | ly += oa # If neg wrap modulo orignal a 127 | return a, lx, ly # Return only positive values 128 | 129 | 130 | def inverse(x: int, n: int) -> int: 131 | """Returns the inverse of x % n under multiplication, a.k.a x^-1 (mod n) 132 | 133 | >>> inverse(7, 4) 134 | 3 135 | >>> (inverse(143, 4) * 143) % 4 136 | 1 137 | """ 138 | 139 | (divider, inv, _) = extended_gcd(x, n) 140 | 141 | if divider != 1: 142 | raise NotRelativePrimeError(x, n, divider) 143 | 144 | return inv 145 | 146 | 147 | def crt(a_values: typing.Iterable[int], modulo_values: typing.Iterable[int]) -> int: 148 | """Chinese Remainder Theorem. 149 | 150 | Calculates x such that x = a[i] (mod m[i]) for each i. 151 | 152 | :param a_values: the a-values of the above equation 153 | :param modulo_values: the m-values of the above equation 154 | :returns: x such that x = a[i] (mod m[i]) for each i 155 | 156 | 157 | >>> crt([2, 3], [3, 5]) 158 | 8 159 | 160 | >>> crt([2, 3, 2], [3, 5, 7]) 161 | 23 162 | 163 | >>> crt([2, 3, 0], [7, 11, 15]) 164 | 135 165 | """ 166 | 167 | m = 1 168 | x = 0 169 | 170 | for modulo in modulo_values: 171 | m *= modulo 172 | 173 | for (m_i, a_i) in zip(modulo_values, a_values): 174 | M_i = m // m_i 175 | inv = inverse(M_i, m_i) 176 | 177 | x = (x + a_i * M_i * inv) % m 178 | 179 | return x 180 | 181 | 182 | if __name__ == '__main__': 183 | import doctest 184 | 185 | doctest.testmod() 186 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa/core.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Sybren A. Stüvel 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Core mathematical operations. 16 | 17 | This is the actual core RSA implementation, which is only defined 18 | mathematically on integers. 19 | """ 20 | 21 | 22 | def assert_int(var: int, name: str) -> None: 23 | if isinstance(var, int): 24 | return 25 | 26 | raise TypeError('%s should be an integer, not %s' % (name, var.__class__)) 27 | 28 | 29 | def encrypt_int(message: int, ekey: int, n: int) -> int: 30 | """Encrypts a message using encryption key 'ekey', working modulo n""" 31 | 32 | assert_int(message, 'message') 33 | assert_int(ekey, 'ekey') 34 | assert_int(n, 'n') 35 | 36 | if message < 0: 37 | raise ValueError('Only non-negative numbers are supported') 38 | 39 | if message > n: 40 | raise OverflowError("The message %i is too long for n=%i" % (message, n)) 41 | 42 | return pow(message, ekey, n) 43 | 44 | 45 | def decrypt_int(cyphertext: int, dkey: int, n: int) -> int: 46 | """Decrypts a cypher text using the decryption key 'dkey', working modulo n""" 47 | 48 | assert_int(cyphertext, 'cyphertext') 49 | assert_int(dkey, 'dkey') 50 | assert_int(n, 'n') 51 | 52 | message = pow(cyphertext, dkey, n) 53 | return message 54 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa/parallel.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Sybren A. Stüvel 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Functions for parallel computation on multiple cores. 16 | 17 | Introduced in Python-RSA 3.1. 18 | 19 | .. note:: 20 | 21 | Requires Python 2.6 or newer. 22 | 23 | """ 24 | 25 | import multiprocessing as mp 26 | from multiprocessing.connection import Connection 27 | 28 | import rsa.prime 29 | import rsa.randnum 30 | 31 | 32 | def _find_prime(nbits: int, pipe: Connection) -> None: 33 | while True: 34 | integer = rsa.randnum.read_random_odd_int(nbits) 35 | 36 | # Test for primeness 37 | if rsa.prime.is_prime(integer): 38 | pipe.send(integer) 39 | return 40 | 41 | 42 | def getprime(nbits: int, poolsize: int) -> int: 43 | """Returns a prime number that can be stored in 'nbits' bits. 44 | 45 | Works in multiple threads at the same time. 46 | 47 | >>> p = getprime(128, 3) 48 | >>> rsa.prime.is_prime(p-1) 49 | False 50 | >>> rsa.prime.is_prime(p) 51 | True 52 | >>> rsa.prime.is_prime(p+1) 53 | False 54 | 55 | >>> from rsa import common 56 | >>> common.bit_size(p) == 128 57 | True 58 | 59 | """ 60 | 61 | (pipe_recv, pipe_send) = mp.Pipe(duplex=False) 62 | 63 | # Create processes 64 | try: 65 | procs = [mp.Process(target=_find_prime, args=(nbits, pipe_send)) 66 | for _ in range(poolsize)] 67 | # Start processes 68 | for p in procs: 69 | p.start() 70 | 71 | result = pipe_recv.recv() 72 | finally: 73 | pipe_recv.close() 74 | pipe_send.close() 75 | 76 | # Terminate processes 77 | for p in procs: 78 | p.terminate() 79 | 80 | return result 81 | 82 | 83 | __all__ = ['getprime'] 84 | 85 | if __name__ == '__main__': 86 | print('Running doctests 1000x or until failure') 87 | import doctest 88 | 89 | for count in range(100): 90 | (failures, tests) = doctest.testmod() 91 | if failures: 92 | break 93 | 94 | if count % 10 == 0 and count: 95 | print('%i times' % count) 96 | 97 | print('Doctests done') 98 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa/pem.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Sybren A. Stüvel 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Functions that load and write PEM-encoded files.""" 16 | 17 | import base64 18 | import typing 19 | 20 | # Should either be ASCII strings or bytes. 21 | FlexiText = typing.Union[str, bytes] 22 | 23 | 24 | def _markers(pem_marker: FlexiText) -> typing.Tuple[bytes, bytes]: 25 | """ 26 | Returns the start and end PEM markers, as bytes. 27 | """ 28 | 29 | if not isinstance(pem_marker, bytes): 30 | pem_marker = pem_marker.encode('ascii') 31 | 32 | return (b'-----BEGIN ' + pem_marker + b'-----', 33 | b'-----END ' + pem_marker + b'-----') 34 | 35 | 36 | def _pem_lines(contents: bytes, pem_start: bytes, pem_end: bytes) -> typing.Iterator[bytes]: 37 | """Generator over PEM lines between pem_start and pem_end.""" 38 | 39 | in_pem_part = False 40 | seen_pem_start = False 41 | 42 | for line in contents.splitlines(): 43 | line = line.strip() 44 | 45 | # Skip empty lines 46 | if not line: 47 | continue 48 | 49 | # Handle start marker 50 | if line == pem_start: 51 | if in_pem_part: 52 | raise ValueError('Seen start marker "%r" twice' % pem_start) 53 | 54 | in_pem_part = True 55 | seen_pem_start = True 56 | continue 57 | 58 | # Skip stuff before first marker 59 | if not in_pem_part: 60 | continue 61 | 62 | # Handle end marker 63 | if in_pem_part and line == pem_end: 64 | in_pem_part = False 65 | break 66 | 67 | # Load fields 68 | if b':' in line: 69 | continue 70 | 71 | yield line 72 | 73 | # Do some sanity checks 74 | if not seen_pem_start: 75 | raise ValueError('No PEM start marker "%r" found' % pem_start) 76 | 77 | if in_pem_part: 78 | raise ValueError('No PEM end marker "%r" found' % pem_end) 79 | 80 | 81 | def load_pem(contents: FlexiText, pem_marker: FlexiText) -> bytes: 82 | """Loads a PEM file. 83 | 84 | :param contents: the contents of the file to interpret 85 | :param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY' 86 | when your file has '-----BEGIN RSA PRIVATE KEY-----' and 87 | '-----END RSA PRIVATE KEY-----' markers. 88 | 89 | :return: the base64-decoded content between the start and end markers. 90 | 91 | @raise ValueError: when the content is invalid, for example when the start 92 | marker cannot be found. 93 | 94 | """ 95 | 96 | # We want bytes, not text. If it's text, it can be converted to ASCII bytes. 97 | if not isinstance(contents, bytes): 98 | contents = contents.encode('ascii') 99 | 100 | (pem_start, pem_end) = _markers(pem_marker) 101 | pem_lines = [line for line in _pem_lines(contents, pem_start, pem_end)] 102 | 103 | # Base64-decode the contents 104 | pem = b''.join(pem_lines) 105 | return base64.standard_b64decode(pem) 106 | 107 | 108 | def save_pem(contents: bytes, pem_marker: FlexiText) -> bytes: 109 | """Saves a PEM file. 110 | 111 | :param contents: the contents to encode in PEM format 112 | :param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY' 113 | when your file has '-----BEGIN RSA PRIVATE KEY-----' and 114 | '-----END RSA PRIVATE KEY-----' markers. 115 | 116 | :return: the base64-encoded content between the start and end markers, as bytes. 117 | 118 | """ 119 | 120 | (pem_start, pem_end) = _markers(pem_marker) 121 | 122 | b64 = base64.standard_b64encode(contents).replace(b'\n', b'') 123 | pem_lines = [pem_start] 124 | 125 | for block_start in range(0, len(b64), 64): 126 | block = b64[block_start:block_start + 64] 127 | pem_lines.append(block) 128 | 129 | pem_lines.append(pem_end) 130 | pem_lines.append(b'') 131 | 132 | return b'\n'.join(pem_lines) 133 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa/pkcs1_v2.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Sybren A. Stüvel 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Functions for PKCS#1 version 2 encryption and signing 16 | 17 | This module implements certain functionality from PKCS#1 version 2. Main 18 | documentation is RFC 2437: https://tools.ietf.org/html/rfc2437 19 | """ 20 | 21 | from rsa import ( 22 | common, 23 | pkcs1, 24 | transform, 25 | ) 26 | 27 | 28 | def mgf1(seed: bytes, length: int, hasher: str = 'SHA-1') -> bytes: 29 | """ 30 | MGF1 is a Mask Generation Function based on a hash function. 31 | 32 | A mask generation function takes an octet string of variable length and a 33 | desired output length as input, and outputs an octet string of the desired 34 | length. The plaintext-awareness of RSAES-OAEP relies on the random nature of 35 | the output of the mask generation function, which in turn relies on the 36 | random nature of the underlying hash. 37 | 38 | :param bytes seed: seed from which mask is generated, an octet string 39 | :param int length: intended length in octets of the mask, at most 2^32(hLen) 40 | :param str hasher: hash function (hLen denotes the length in octets of the hash 41 | function output) 42 | 43 | :return: mask, an octet string of length `length` 44 | :rtype: bytes 45 | 46 | :raise OverflowError: when `length` is too large for the specified `hasher` 47 | :raise ValueError: when specified `hasher` is invalid 48 | """ 49 | 50 | try: 51 | hash_length = pkcs1.HASH_METHODS[hasher]().digest_size 52 | except KeyError: 53 | raise ValueError( 54 | 'Invalid `hasher` specified. Please select one of: {hash_list}'.format( 55 | hash_list=', '.join(sorted(pkcs1.HASH_METHODS.keys())) 56 | ) 57 | ) 58 | 59 | # If l > 2^32(hLen), output "mask too long" and stop. 60 | if length > (2**32 * hash_length): 61 | raise OverflowError( 62 | "Desired length should be at most 2**32 times the hasher's output " 63 | "length ({hash_length} for {hasher} function)".format( 64 | hash_length=hash_length, 65 | hasher=hasher, 66 | ) 67 | ) 68 | 69 | # Looping `counter` from 0 to ceil(l / hLen)-1, build `output` based on the 70 | # hashes formed by (`seed` + C), being `C` an octet string of length 4 71 | # generated by converting `counter` with the primitive I2OSP 72 | output = b''.join( 73 | pkcs1.compute_hash( 74 | seed + transform.int2bytes(counter, fill_size=4), 75 | method_name=hasher, 76 | ) 77 | for counter in range(common.ceil_div(length, hash_length) + 1) 78 | ) 79 | 80 | # Output the leading `length` octets of `output` as the octet string mask. 81 | return output[:length] 82 | 83 | 84 | __all__ = [ 85 | 'mgf1', 86 | ] 87 | 88 | if __name__ == '__main__': 89 | print('Running doctests 1000x or until failure') 90 | import doctest 91 | 92 | for count in range(1000): 93 | (failures, tests) = doctest.testmod() 94 | if failures: 95 | break 96 | 97 | if count % 100 == 0 and count: 98 | print('%i times' % count) 99 | 100 | print('Doctests done') 101 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa/prime.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Sybren A. Stüvel 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Numerical functions related to primes. 16 | 17 | Implementation based on the book Algorithm Design by Michael T. Goodrich and 18 | Roberto Tamassia, 2002. 19 | """ 20 | 21 | import rsa.common 22 | import rsa.randnum 23 | 24 | __all__ = ['getprime', 'are_relatively_prime'] 25 | 26 | 27 | def gcd(p: int, q: int) -> int: 28 | """Returns the greatest common divisor of p and q 29 | 30 | >>> gcd(48, 180) 31 | 12 32 | """ 33 | 34 | while q != 0: 35 | (p, q) = (q, p % q) 36 | return p 37 | 38 | 39 | def get_primality_testing_rounds(number: int) -> int: 40 | """Returns minimum number of rounds for Miller-Rabing primality testing, 41 | based on number bitsize. 42 | 43 | According to NIST FIPS 186-4, Appendix C, Table C.3, minimum number of 44 | rounds of M-R testing, using an error probability of 2 ** (-100), for 45 | different p, q bitsizes are: 46 | * p, q bitsize: 512; rounds: 7 47 | * p, q bitsize: 1024; rounds: 4 48 | * p, q bitsize: 1536; rounds: 3 49 | See: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf 50 | """ 51 | 52 | # Calculate number bitsize. 53 | bitsize = rsa.common.bit_size(number) 54 | # Set number of rounds. 55 | if bitsize >= 1536: 56 | return 3 57 | if bitsize >= 1024: 58 | return 4 59 | if bitsize >= 512: 60 | return 7 61 | # For smaller bitsizes, set arbitrary number of rounds. 62 | return 10 63 | 64 | 65 | def miller_rabin_primality_testing(n: int, k: int) -> bool: 66 | """Calculates whether n is composite (which is always correct) or prime 67 | (which theoretically is incorrect with error probability 4**-k), by 68 | applying Miller-Rabin primality testing. 69 | 70 | For reference and implementation example, see: 71 | https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test 72 | 73 | :param n: Integer to be tested for primality. 74 | :type n: int 75 | :param k: Number of rounds (witnesses) of Miller-Rabin testing. 76 | :type k: int 77 | :return: False if the number is composite, True if it's probably prime. 78 | :rtype: bool 79 | """ 80 | 81 | # prevent potential infinite loop when d = 0 82 | if n < 2: 83 | return False 84 | 85 | # Decompose (n - 1) to write it as (2 ** r) * d 86 | # While d is even, divide it by 2 and increase the exponent. 87 | d = n - 1 88 | r = 0 89 | 90 | while not (d & 1): 91 | r += 1 92 | d >>= 1 93 | 94 | # Test k witnesses. 95 | for _ in range(k): 96 | # Generate random integer a, where 2 <= a <= (n - 2) 97 | a = rsa.randnum.randint(n - 3) + 1 98 | 99 | x = pow(a, d, n) 100 | if x == 1 or x == n - 1: 101 | continue 102 | 103 | for _ in range(r - 1): 104 | x = pow(x, 2, n) 105 | if x == 1: 106 | # n is composite. 107 | return False 108 | if x == n - 1: 109 | # Exit inner loop and continue with next witness. 110 | break 111 | else: 112 | # If loop doesn't break, n is composite. 113 | return False 114 | 115 | return True 116 | 117 | 118 | def is_prime(number: int) -> bool: 119 | """Returns True if the number is prime, and False otherwise. 120 | 121 | >>> is_prime(2) 122 | True 123 | >>> is_prime(42) 124 | False 125 | >>> is_prime(41) 126 | True 127 | """ 128 | 129 | # Check for small numbers. 130 | if number < 10: 131 | return number in {2, 3, 5, 7} 132 | 133 | # Check for even numbers. 134 | if not (number & 1): 135 | return False 136 | 137 | # Calculate minimum number of rounds. 138 | k = get_primality_testing_rounds(number) 139 | 140 | # Run primality testing with (minimum + 1) rounds. 141 | return miller_rabin_primality_testing(number, k + 1) 142 | 143 | 144 | def getprime(nbits: int) -> int: 145 | """Returns a prime number that can be stored in 'nbits' bits. 146 | 147 | >>> p = getprime(128) 148 | >>> is_prime(p-1) 149 | False 150 | >>> is_prime(p) 151 | True 152 | >>> is_prime(p+1) 153 | False 154 | 155 | >>> from rsa import common 156 | >>> common.bit_size(p) == 128 157 | True 158 | """ 159 | 160 | assert nbits > 3 # the loop wil hang on too small numbers 161 | 162 | while True: 163 | integer = rsa.randnum.read_random_odd_int(nbits) 164 | 165 | # Test for primeness 166 | if is_prime(integer): 167 | return integer 168 | 169 | # Retry if not prime 170 | 171 | 172 | def are_relatively_prime(a: int, b: int) -> bool: 173 | """Returns True if a and b are relatively prime, and False if they 174 | are not. 175 | 176 | >>> are_relatively_prime(2, 3) 177 | True 178 | >>> are_relatively_prime(2, 4) 179 | False 180 | """ 181 | 182 | d = gcd(a, b) 183 | return d == 1 184 | 185 | 186 | if __name__ == '__main__': 187 | print('Running doctests 1000x or until failure') 188 | import doctest 189 | 190 | for count in range(1000): 191 | (failures, tests) = doctest.testmod() 192 | if failures: 193 | break 194 | 195 | if count % 100 == 0 and count: 196 | print('%i times' % count) 197 | 198 | print('Doctests done') 199 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa/randnum.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Sybren A. Stüvel 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Functions for generating random numbers.""" 16 | 17 | # Source inspired by code by Yesudeep Mangalapilly 18 | 19 | import os 20 | import struct 21 | 22 | from rsa import common, transform 23 | 24 | 25 | def read_random_bits(nbits: int) -> bytes: 26 | """Reads 'nbits' random bits. 27 | 28 | If nbits isn't a whole number of bytes, an extra byte will be appended with 29 | only the lower bits set. 30 | """ 31 | 32 | nbytes, rbits = divmod(nbits, 8) 33 | 34 | # Get the random bytes 35 | randomdata = os.urandom(nbytes) 36 | 37 | # Add the remaining random bits 38 | if rbits > 0: 39 | randomvalue = ord(os.urandom(1)) 40 | randomvalue >>= (8 - rbits) 41 | randomdata = struct.pack("B", randomvalue) + randomdata 42 | 43 | return randomdata 44 | 45 | 46 | def read_random_int(nbits: int) -> int: 47 | """Reads a random integer of approximately nbits bits. 48 | """ 49 | 50 | randomdata = read_random_bits(nbits) 51 | value = transform.bytes2int(randomdata) 52 | 53 | # Ensure that the number is large enough to just fill out the required 54 | # number of bits. 55 | value |= 1 << (nbits - 1) 56 | 57 | return value 58 | 59 | 60 | def read_random_odd_int(nbits: int) -> int: 61 | """Reads a random odd integer of approximately nbits bits. 62 | 63 | >>> read_random_odd_int(512) & 1 64 | 1 65 | """ 66 | 67 | value = read_random_int(nbits) 68 | 69 | # Make sure it's odd 70 | return value | 1 71 | 72 | 73 | def randint(maxvalue: int) -> int: 74 | """Returns a random integer x with 1 <= x <= maxvalue 75 | 76 | May take a very long time in specific situations. If maxvalue needs N bits 77 | to store, the closer maxvalue is to (2 ** N) - 1, the faster this function 78 | is. 79 | """ 80 | 81 | bit_size = common.bit_size(maxvalue) 82 | 83 | tries = 0 84 | while True: 85 | value = read_random_int(bit_size) 86 | if value <= maxvalue: 87 | break 88 | 89 | if tries % 10 == 0 and tries: 90 | # After a lot of tries to get the right number of bits but still 91 | # smaller than maxvalue, decrease the number of bits by 1. That'll 92 | # dramatically increase the chances to get a large enough number. 93 | bit_size -= 1 94 | tries += 1 95 | 96 | return value 97 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa/transform.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Sybren A. Stüvel 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Data transformation functions. 16 | 17 | From bytes to a number, number to bytes, etc. 18 | """ 19 | 20 | import math 21 | 22 | 23 | def bytes2int(raw_bytes: bytes) -> int: 24 | r"""Converts a list of bytes or an 8-bit string to an integer. 25 | 26 | When using unicode strings, encode it to some encoding like UTF8 first. 27 | 28 | >>> (((128 * 256) + 64) * 256) + 15 29 | 8405007 30 | >>> bytes2int(b'\x80@\x0f') 31 | 8405007 32 | 33 | """ 34 | return int.from_bytes(raw_bytes, 'big', signed=False) 35 | 36 | 37 | def int2bytes(number: int, fill_size: int = 0) -> bytes: 38 | """ 39 | Convert an unsigned integer to bytes (big-endian):: 40 | 41 | Does not preserve leading zeros if you don't specify a fill size. 42 | 43 | :param number: 44 | Integer value 45 | :param fill_size: 46 | If the optional fill size is given the length of the resulting 47 | byte string is expected to be the fill size and will be padded 48 | with prefix zero bytes to satisfy that length. 49 | :returns: 50 | Raw bytes (base-256 representation). 51 | :raises: 52 | ``OverflowError`` when fill_size is given and the number takes up more 53 | bytes than fit into the block. This requires the ``overflow`` 54 | argument to this function to be set to ``False`` otherwise, no 55 | error will be raised. 56 | """ 57 | 58 | if number < 0: 59 | raise ValueError("Number must be an unsigned integer: %d" % number) 60 | 61 | bytes_required = max(1, math.ceil(number.bit_length() / 8)) 62 | 63 | if fill_size > 0: 64 | return number.to_bytes(fill_size, 'big') 65 | 66 | return number.to_bytes(bytes_required, 'big') 67 | 68 | 69 | if __name__ == '__main__': 70 | import doctest 71 | 72 | doctest.testmod() 73 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa/util.py: -------------------------------------------------------------------------------- 1 | # Copyright 2011 Sybren A. Stüvel 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Utility functions.""" 16 | 17 | import sys 18 | from optparse import OptionParser 19 | 20 | import rsa.key 21 | 22 | 23 | def private_to_public() -> None: 24 | """Reads a private key and outputs the corresponding public key.""" 25 | 26 | # Parse the CLI options 27 | parser = OptionParser(usage='usage: %prog [options]', 28 | description='Reads a private key and outputs the ' 29 | 'corresponding public key. Both private and public keys use ' 30 | 'the format described in PKCS#1 v1.5') 31 | 32 | parser.add_option('-i', '--input', dest='infilename', type='string', 33 | help='Input filename. Reads from stdin if not specified') 34 | parser.add_option('-o', '--output', dest='outfilename', type='string', 35 | help='Output filename. Writes to stdout of not specified') 36 | 37 | parser.add_option('--inform', dest='inform', 38 | help='key format of input - default PEM', 39 | choices=('PEM', 'DER'), default='PEM') 40 | 41 | parser.add_option('--outform', dest='outform', 42 | help='key format of output - default PEM', 43 | choices=('PEM', 'DER'), default='PEM') 44 | 45 | (cli, cli_args) = parser.parse_args(sys.argv) 46 | 47 | # Read the input data 48 | if cli.infilename: 49 | print('Reading private key from %s in %s format' % 50 | (cli.infilename, cli.inform), file=sys.stderr) 51 | with open(cli.infilename, 'rb') as infile: 52 | in_data = infile.read() 53 | else: 54 | print('Reading private key from stdin in %s format' % cli.inform, 55 | file=sys.stderr) 56 | in_data = sys.stdin.read().encode('ascii') 57 | 58 | assert type(in_data) == bytes, type(in_data) 59 | 60 | # Take the public fields and create a public key 61 | priv_key = rsa.key.PrivateKey.load_pkcs1(in_data, cli.inform) 62 | pub_key = rsa.key.PublicKey(priv_key.n, priv_key.e) 63 | 64 | # Save to the output file 65 | out_data = pub_key.save_pkcs1(cli.outform) 66 | 67 | if cli.outfilename: 68 | print('Writing public key to %s in %s format' % 69 | (cli.outfilename, cli.outform), file=sys.stderr) 70 | with open(cli.outfilename, 'wb') as outfile: 71 | outfile.write(out_data) 72 | else: 73 | print('Writing public key to stdout in %s format' % cli.outform, 74 | file=sys.stderr) 75 | sys.stdout.write(out_data.decode('ascii')) 76 | -------------------------------------------------------------------------------- /天翼云盘签到/rsa/varblock.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Copyright 2011 Sybren A. Stüvel 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """VARBLOCK file support 18 | 19 | .. deprecated:: 3.4 20 | 21 | The VARBLOCK format is NOT recommended for general use, has been deprecated since 22 | Python-RSA 3.4, and will be removed in a future release. It's vulnerable to a 23 | number of attacks: 24 | 25 | 1. decrypt/encrypt_bigfile() does not implement `Authenticated encryption`_ nor 26 | uses MACs to verify messages before decrypting public key encrypted messages. 27 | 28 | 2. decrypt/encrypt_bigfile() does not use hybrid encryption (it uses plain RSA) 29 | and has no method for chaining, so block reordering is possible. 30 | 31 | See `issue #19 on Github`_ for more information. 32 | 33 | .. _Authenticated encryption: https://en.wikipedia.org/wiki/Authenticated_encryption 34 | .. _issue #19 on Github: https://github.com/sybrenstuvel/python-rsa/issues/13 35 | 36 | 37 | The VARBLOCK file format is as follows, where || denotes byte concatenation: 38 | 39 | FILE := VERSION || BLOCK || BLOCK ... 40 | 41 | BLOCK := LENGTH || DATA 42 | 43 | LENGTH := varint-encoded length of the subsequent data. Varint comes from 44 | Google Protobuf, and encodes an integer into a variable number of bytes. 45 | Each byte uses the 7 lowest bits to encode the value. The highest bit set 46 | to 1 indicates the next byte is also part of the varint. The last byte will 47 | have this bit set to 0. 48 | 49 | This file format is called the VARBLOCK format, in line with the varint format 50 | used to denote the block sizes. 51 | 52 | """ 53 | 54 | import warnings 55 | 56 | from rsa._compat import byte, b 57 | 58 | ZERO_BYTE = b('\x00') 59 | VARBLOCK_VERSION = 1 60 | 61 | warnings.warn("The 'rsa.varblock' module was deprecated in Python-RSA version " 62 | "3.4 due to security issues in the VARBLOCK format. See " 63 | "https://github.com/sybrenstuvel/python-rsa/issues/13 for more information.", 64 | DeprecationWarning) 65 | 66 | 67 | def read_varint(infile): 68 | """Reads a varint from the file. 69 | 70 | When the first byte to be read indicates EOF, (0, 0) is returned. When an 71 | EOF occurs when at least one byte has been read, an EOFError exception is 72 | raised. 73 | 74 | :param infile: the file-like object to read from. It should have a read() 75 | method. 76 | :returns: (varint, length), the read varint and the number of read bytes. 77 | """ 78 | 79 | varint = 0 80 | read_bytes = 0 81 | 82 | while True: 83 | char = infile.read(1) 84 | if len(char) == 0: 85 | if read_bytes == 0: 86 | return 0, 0 87 | raise EOFError('EOF while reading varint, value is %i so far' % 88 | varint) 89 | 90 | byte = ord(char) 91 | varint += (byte & 0x7F) << (7 * read_bytes) 92 | 93 | read_bytes += 1 94 | 95 | if not byte & 0x80: 96 | return varint, read_bytes 97 | 98 | 99 | def write_varint(outfile, value): 100 | """Writes a varint to a file. 101 | 102 | :param outfile: the file-like object to write to. It should have a write() 103 | method. 104 | :returns: the number of written bytes. 105 | """ 106 | 107 | # there is a big difference between 'write the value 0' (this case) and 108 | # 'there is nothing left to write' (the false-case of the while loop) 109 | 110 | if value == 0: 111 | outfile.write(ZERO_BYTE) 112 | return 1 113 | 114 | written_bytes = 0 115 | while value > 0: 116 | to_write = value & 0x7f 117 | value >>= 7 118 | 119 | if value > 0: 120 | to_write |= 0x80 121 | 122 | outfile.write(byte(to_write)) 123 | written_bytes += 1 124 | 125 | return written_bytes 126 | 127 | 128 | def yield_varblocks(infile): 129 | """Generator, yields each block in the input file. 130 | 131 | :param infile: file to read, is expected to have the VARBLOCK format as 132 | described in the module's docstring. 133 | @yields the contents of each block. 134 | """ 135 | 136 | # Check the version number 137 | first_char = infile.read(1) 138 | if len(first_char) == 0: 139 | raise EOFError('Unable to read VARBLOCK version number') 140 | 141 | version = ord(first_char) 142 | if version != VARBLOCK_VERSION: 143 | raise ValueError('VARBLOCK version %i not supported' % version) 144 | 145 | while True: 146 | (block_size, read_bytes) = read_varint(infile) 147 | 148 | # EOF at block boundary, that's fine. 149 | if read_bytes == 0 and block_size == 0: 150 | break 151 | 152 | block = infile.read(block_size) 153 | 154 | read_size = len(block) 155 | if read_size != block_size: 156 | raise EOFError('Block size is %i, but could read only %i bytes' % 157 | (block_size, read_size)) 158 | 159 | yield block 160 | 161 | 162 | def yield_fixedblocks(infile, blocksize): 163 | """Generator, yields each block of ``blocksize`` bytes in the input file. 164 | 165 | :param infile: file to read and separate in blocks. 166 | :returns: a generator that yields the contents of each block 167 | """ 168 | 169 | while True: 170 | block = infile.read(blocksize) 171 | 172 | read_bytes = len(block) 173 | if read_bytes == 0: 174 | break 175 | 176 | yield block 177 | 178 | if read_bytes < blocksize: 179 | break 180 | -------------------------------------------------------------------------------- /百度贴吧签到/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "serverless-cloud-function-application": { 3 | "application":{ 4 | "Chinese":{ 5 | "name": "helloworld", 6 | "description": "helloworld 空白模板函数", 7 | "attention": "无", 8 | "readme": { 9 | "file": "", 10 | "content": "" 11 | }, 12 | "license": { 13 | "file": "", 14 | "content": "公开" 15 | }, 16 | "author": { 17 | "name": "腾讯云无服务器云函数团队" 18 | } 19 | }, 20 | "English":{ 21 | "name": "helloworld", 22 | "description": "This is helloworld function", 23 | "attention": "No", 24 | "readme": { 25 | "file": "", // readme file 26 | "content": "" //content of readme 27 | }, 28 | "license": { 29 | "file": "", // license file 30 | "content": "Open" //content of license 31 | }, 32 | "author": { 33 | "name": "Tencent Cloud Serverless Team" // author 34 | } 35 | }, 36 | "input_parameters":{ 37 | "event":"", 38 | "context":"" 39 | }, 40 | "output_parameters":{ 41 | }, 42 | "download_address":"https://github.com/tencentyun/scf-demo-repo/tree/master/Python3.6-helloworld", //Demo's git download url. demo的git下载链接 43 | "tags":[ 44 | "Python3.6", "helloworld" 45 | // The tags only support English and can be multiple, we suggest you to use keywords such as runtime, trigger, environment and so on. 46 | // 标签统一为英文,可编写多个,建议使用runtime、触发器、场景等关键字,用户可以通过该关键字搜索。前台需要展示,请认真填写,不支持中文 47 | ], 48 | "version": "1.0.3" 49 | // Version number, which identifies the demo version status. 50 | // Demo will not to update to the page if the version number unmodified. 51 | //版本号,通过版本号标识 demo 升级情况,未修改版本号会导致 demo 不更新至页面 52 | }, 53 | "functions": { 54 | "name": "helloworld", // Function name which only be in English. 函数名称,只支持英文 55 | "description": "helloworld blank template function. Helloworld空白模板函数", 56 | "handler":"index.main_handler", 57 | "memorySize": 128, // Running memory. 运行配置内存 58 | "timeout": 3, // Running timeout. 运行超时时间 59 | "runtime": "Python3.6", // Runtime which users can search demo by this keyword. 运行环境,用户可以通过该关键字搜索["Python2.7", "Python3.6", "Nodejs6.10", "Java8", "LuaCDN", "NodejsCDN", "Php5", "Php7", "Nodejs8.9", "Go1"] 60 | "Environment":{ 61 | }, // Optional, used to define environment variables. 可选,用于定义环境变量 62 | "Events":{ 63 | }, // Optional, used define the event source that triggers this function. 可选,用于定义触发此函数的事件源 64 | "VpcConfig":{ 65 | }, // Optional, used configure cloud function's private network. 可选, 用于配置云函数访问 VPC 私有网络。 66 | "codeObject": { 67 | "codeFile": [ 68 | "index.py" 69 | ], 70 | "CodeUri":[ // Code download url which should be same as 'download_address'. 代码下载地址,和download_address保持一致 71 | "https://github.com/tencentyun/scf-demo-repo/tree/master/Python3.6-helloworld" 72 | ] 73 | } 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /百度贴吧签到/index.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf8 -*- 2 | # -*- coding: utf8 -*- 3 | from requests import Session 4 | from time import sleep 5 | from random import randint 6 | import requests 7 | 8 | sckey = '' 9 | 10 | def main2(*args): 11 | sleep(randint(0, 10)) 12 | # 数据 13 | like_url = 'https://tieba.baidu.com/mo/q/newmoindex?' 14 | sign_url = 'http://tieba.baidu.com/sign/add' 15 | tbs = '4fb45fea4498360d1547435295' 16 | head = { 17 | 'Accept': 'text/html, */*; q=0.01', 18 | 'Accept-Encoding': 'gzip, deflate', 19 | 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8', 20 | 'Connection': 'keep-alive', 21 | 'Cookie': 'BDUSS=WxVT0FzZn5JYUNHan5YR2FYUHZDRnp1MThqVHdGN2ZpVEM1bnUxR1VJaDd0RWhmRVFBQUFBJCQAAAAAAAAAAAEAAABdKY860e7OxND91NrCt8nPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHsnIV97JyFfb; BDUSS_BFESS=WxVT0FzZn5JYUNHan5YR2FYUHZDRnp1MThqVHdGN2ZpVEM1bnUxR1VJaDd0RWhmRVFBQUFBJCQAAAAAAAAAAAEAAABdKY860e7OxND91NrCt8nPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHsnIV97JyFfb;STOKEN=d38e3183bf24cfb2e40cdb6649c5fc6032097d0a3598a1ded5d3ed54c18ea602', 22 | 'Host': 'tieba.baidu.com', 23 | 'Referer': 'http://tieba.baidu.com/i/i/forum', 24 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 25 | 'Chrome/71.0.3578.98 Safari/537.36', 26 | 'X-Requested-With': 'XMLHttpRequest'} 27 | s = Session() 28 | 29 | 30 | # 获取关注的贴吧 31 | bars = [] 32 | dic = s.get(like_url, headers=head).json()['data']['like_forum'] 33 | for bar_info in dic: 34 | bars.append(bar_info['forum_name']) 35 | 36 | 37 | # 签到 38 | already_signed_code = 1101 39 | success_code = 0 40 | need_verify_code = 2150040 41 | already_signed = 0 42 | succees = 0 43 | failed_bar = [] 44 | n = 0 45 | sleep(randint(0, 10)) 46 | 47 | while n < len(bars): 48 | sleep(0.5) 49 | bar = bars[n] 50 | data = { 51 | 'ie': 'utf-8', 52 | 'kw': bar, 53 | 'tbs': tbs 54 | } 55 | try: 56 | r = s.post(sign_url, data=data, headers=head) 57 | except Exception as e: 58 | print(f'未能签到{bar}, 由于{e}。') 59 | failed_bar.append(bar) 60 | continue 61 | dic = r.json() 62 | msg = dic['no'] 63 | if msg == already_signed_code: already_signed += 1; r = '已经签到过了!' 64 | elif msg == need_verify_code: n -= 1; r = '需要验证码,即将重试!' 65 | elif msg == success_code: r = f"签到成功!你是第{dic['data']['uinfo']['user_sign_rank']}个签到的吧友,共签到{dic['data']['uinfo']['total_sign_num']}天。" 66 | else: r = '未知错误!' + dic['error'] 67 | print(f"{bar}:{r}") 68 | succees += 1 69 | n += 1 70 | l = len(bars) 71 | failed = "\n失败列表:"+'\n'.join(failed_bar) if len(failed_bar) else '' 72 | bai=f'''共{l}个吧,其中: {succees}个吧签到成功,{len(failed_bar)}个吧签到失败,{already_signed}个吧已经签到。{failed}''' 73 | print(f'''共{l}个吧,其中: {succees}个吧签到成功,{len(failed_bar)}个吧签到失败,{already_signed}个吧已经签到。{failed}''') 74 | requests.get('https://sc.ftqq.com/' + sckey + '.send?text=百度贴吧签到通知&desp=' + bai) 75 | def main_handler(event, context): 76 | main2() -------------------------------------------------------------------------------- /网易云音乐/account.json: -------------------------------------------------------------------------------- 1 | # 多账号存放文件 2 | 3 | [ 4 | { 5 | "account": "2767***@qq.com", 6 | "password": "bfa834f7de58cb650ca01edb********", 7 | "sckey": "SCU57117T8c9c5ce60bd629112bd2286fcc5f76f65d4bdc5e43592" 8 | }, 9 | { 10 | "account": "150********", 11 | "password": "bfa834f7de58cb650ca01edb********", 12 | "sckey": "SCU97783T70c13167b4daa422f4d419a765eb4ebb5ebc9********" 13 | }, 14 | { 15 | "account": "132********", 16 | "password": "f391235b15781c95384cd5bb********", 17 | "sckey": "SCU97783T70c13167b4daa422f4d419a765eb4ebb5ebc9********" 18 | } 19 | ] -------------------------------------------------------------------------------- /网易云音乐/index.py: -------------------------------------------------------------------------------- 1 | # 主程序 2 | 3 | 4 | #coding:utf-8 5 | ''' 6 | @author: ZainCheung 7 | @LastEditors: ZainCheung 8 | @description:网易云音乐全自动每日打卡云函数版 9 | @Date: 2020-06-25 14:28:48 10 | @LastEditTime: 2020-06-26 17:38:18 11 | ''' 12 | from configparser import ConfigParser 13 | from threading import Timer 14 | import requests 15 | import random 16 | import hashlib 17 | import datetime 18 | import time 19 | import json 20 | import logging 21 | 22 | logger = logging.getLogger() 23 | grade = [10,40,70,130,200,400,1000,3000,8000,20000] 24 | api = '' 25 | 26 | class Task(object): 27 | 28 | ''' 29 | 对象的构造函数 30 | ''' 31 | def __init__(self, uin, pwd, sckey): 32 | self.uin = uin 33 | self.pwd = pwd 34 | self.sckey = sckey 35 | 36 | ''' 37 | 带上用户的cookie去发送数据 38 | url:完整的URL路径 39 | postJson:要以post方式发送的数据 40 | 返回response 41 | ''' 42 | def getResponse(self, url, postJson): 43 | response = requests.post(url, data=postJson, headers={'Content-Type':'application/x-www-form-urlencoded'},cookies=self.cookies) 44 | return response 45 | 46 | ''' 47 | 登陆 48 | ''' 49 | def login(self): 50 | data = {"uin":self.uin,"pwd":self.pwd,"r":random.random()} 51 | if '@' in self.uin: 52 | url = api + '?do=email' 53 | else: 54 | url = api + '?do=login' 55 | response = requests.post(url, data=data, headers={'Content-Type':'application/x-www-form-urlencoded'}) 56 | code = json.loads(response.text)['code'] 57 | self.name = json.loads(response.text)['profile']['nickname'] 58 | self.uid = json.loads(response.text)['account']['id'] 59 | if code==200: 60 | self.error = '' 61 | else: 62 | self.error = '登陆失败,请检查账号' 63 | self.cookies = response.cookies.get_dict() 64 | self.log('登陆成功') 65 | logger.info("登陆成功") 66 | 67 | ''' 68 | 每日签到 69 | ''' 70 | def sign(self): 71 | url = api + '?do=sign' 72 | response = self.getResponse(url, {"r":random.random()}) 73 | data = json.loads(response.text) 74 | if data['code'] == 200: 75 | self.log('签到成功') 76 | logger.info('签到成功') 77 | else: 78 | self.log('重复签到') 79 | logger.info('重复签到') 80 | 81 | ''' 82 | 每日打卡300首歌 83 | ''' 84 | def daka(self): 85 | url = api + '?do=daka' 86 | response = self.getResponse(url, {"r":random.random()}) 87 | self.log(response.text) 88 | 89 | ''' 90 | 查询用户详情 91 | ''' 92 | def detail(self): 93 | url = api + '?do=detail' 94 | data = {"uid":self.uid, "r":random.random()} 95 | response = self.getResponse(url, data) 96 | data = json.loads(response.text) 97 | self.level = data['level'] 98 | self.listenSongs = data['listenSongs'] 99 | self.log('获取用户详情成功') 100 | logger.info('获取用户详情成功') 101 | 102 | ''' 103 | Server推送 104 | ''' 105 | def server(self): 106 | if self.sckey == '': 107 | return 108 | url = 'https://sc.ftqq.com/' + self.sckey + '.send' 109 | self.diyText() # 构造发送内容 110 | response = requests.get(url,params={"text":self.title, "desp":self.content}) 111 | data = json.loads(response.text) 112 | if data['errno'] == 0: 113 | self.log('用户:' + self.name + ' Server酱推送成功') 114 | logger.info('用户:' + self.name + ' Server酱推送成功') 115 | else: 116 | self.log('用户:' + self.name + ' Server酱推送失败,请检查sckey是否正确') 117 | logger.info('用户:' + self.name + ' Server酱推送失败,请检查sckey是否正确') 118 | 119 | ''' 120 | 自定义要推送到微信的内容 121 | title:消息的标题 122 | content:消息的内容,支持MarkDown格式 123 | ''' 124 | def diyText(self): 125 | today = datetime.date.today() 126 | 127 | kaoyan_day = datetime.date(2020,7,16) # 倒计时 128 | date = (kaoyan_day - today).days 129 | 130 | #love_day = datetime.date(2020,12,21) # 纪念日计算比如和对象在一起xx天 131 | #date = (today - love_day).days 132 | 133 | one = requests.get('https://api.qinor.cn/soup/').text # 每日一句的api 134 | for count in grade: 135 | if self.level < 10: 136 | if self.listenSongs < 20000: 137 | if self.listenSongs < count: 138 | self.tip = '还需听歌' + str(count-self.listenSongs) + '首即可升级' 139 | break 140 | else: 141 | self.tip = '你已经听够20000首歌曲,如果登陆天数达到800天即可满级' 142 | else: 143 | self.tip = '恭喜你已经满级!' 144 | if self.error == '': 145 | state = '目前已完成签到,300百首歌也已听完' 146 | self.title = '网易云听歌任务已完成' 147 | else: 148 | state = self.error 149 | self.title = '网易云听歌任务出现问题!' 150 | self.content = ("> tip:等级数据每天下午2点更新 \n\n" 151 | "------\n" 152 | "| 用户名 | " + str(self.name) + " |\n" 153 | "| -------- | :----------------: |\n" 154 | "| 当前等级 | " + str(self.level) + "级 |\n" 155 | "| 累计播放 | " + str(self.listenSongs) + "首 |\n" 156 | "| 升级提示 | " + self.tip + " |\n" 157 | "------\n" 158 | "### 任务状态\n" + str(state) + "\n\n" 159 | 160 | "### 期末倒计时\n距考试还有" + str(date) + "天,主人要加油学习啊\n" #对应上面的倒计时 161 | # "### 已经在一起" + str(date) + "天啦!\n" #对应上面的纪念日 162 | "### 今日一句\n" + one + "\n\n") 163 | 164 | ''' 165 | 打印日志 166 | ''' 167 | def log(self, text): 168 | time_stamp = datetime.datetime.now() 169 | print(time_stamp.strftime('%Y.%m.%d-%H:%M:%S') + ' ' + str(text)) 170 | 171 | ''' 172 | 开始执行 173 | ''' 174 | def start(self): 175 | try: 176 | self.login() 177 | self.sign() 178 | self.detail() 179 | for i in range(1,5): # 5表示刷4次310首歌,根据需求自行修改后面的5 180 | self.daka() 181 | self.log('用户:' + self.name + ' 第' + str(i) + '次打卡成功,即将休眠15秒') 182 | logger.info('用户:' + self.name + ' 第' + str(i) + '次打卡成功,即将休眠15秒') 183 | time.sleep(15) #休眠时间(每次打卡间隔时间),根据需求自行修改 184 | self.server() 185 | except: 186 | self.log('用户任务执行中断,请检查账号密码是否正确') 187 | logger.error('用户任务执行中断,请检查账号密码是否正确========================================') 188 | else: 189 | self.log('用户:' + self.name + ' 今日任务已完成') 190 | logger.info('用户:' + self.name + ' 今日任务已完成========================================') 191 | 192 | 193 | ''' 194 | 初始化:读取配置,配置文件为init.config 195 | 返回字典类型的配置对象 196 | ''' 197 | def init(): 198 | global api # 初始化时设置api 199 | config = ConfigParser() 200 | config.read('init.config', encoding='UTF-8-sig') 201 | uin = config['token']['account'] 202 | pwd = config['token']['password'] 203 | api = config['setting']['api'] 204 | md5Switch = config.getboolean('setting','md5Switch') 205 | peopleSwitch = config.getboolean('setting','peopleSwitch') 206 | sckey = config['setting']['sckey'] 207 | logger.info('配置文件读取完毕') 208 | conf = { 209 | 'uin': uin, 210 | 'pwd': pwd, 211 | 'api': api, 212 | 'md5Switch': md5Switch, 213 | 'peopleSwitch':peopleSwitch, 214 | 'sckey':sckey 215 | } 216 | return conf 217 | 218 | ''' 219 | MD5加密 220 | str:待加密字符 221 | 返回加密后的字符 222 | ''' 223 | def md5(str): 224 | hl = hashlib.md5() 225 | hl.update(str.encode(encoding='utf-8')) 226 | return hl.hexdigest() 227 | 228 | ''' 229 | 加载Json文件 230 | jsonPath:json文件的名字,例如account.json 231 | ''' 232 | def loadJson(jsonPath): 233 | with open(jsonPath,encoding='utf-8') as f: 234 | account = json.load(f) 235 | return account 236 | 237 | ''' 238 | 检查api 239 | ''' 240 | def check(): 241 | url = api + '?do=check' 242 | respones = requests.get(url) 243 | if respones.status_code == 200: 244 | logger.info('api测试正常') 245 | else: 246 | logger.error('api测试异常') 247 | 248 | ''' 249 | 任务池 250 | ''' 251 | def taskPool(): 252 | 253 | config = init() 254 | check() # 每天对api做一次检查 255 | if config['peopleSwitch'] is True: 256 | logger.info('多人开关已打开,即将执行进行多人任务') 257 | account = loadJson("account.json") 258 | for man in account: 259 | logger.info('账号: ' + man['account'] + ' 开始执行========================================') 260 | task = Task(man['account'], man['password'], man['sckey']) 261 | task.start() 262 | time.sleep(10) 263 | logger.info('所有账号已全部完成任务,服务进入休眠中,等待明天重新启动') 264 | else : 265 | logger.info('账号: ' + config['uin'] + ' 开始执行========================================') 266 | if config['md5Switch'] is True: 267 | logger.info('MD5开关已打开,即将开始为你加密,密码不会上传至服务器,请知悉') 268 | config['pwd'] = md5(config['pwd']) 269 | task = Task(config['uin'], config['pwd'], config['sckey']) 270 | task.start() 271 | 272 | ''' 273 | 程序的入口 274 | ''' 275 | def main(event,content): 276 | taskPool() 277 | -------------------------------------------------------------------------------- /网易云音乐/init.config: -------------------------------------------------------------------------------- 1 | # 配置文件 2 | # setting.config(UTF-8) 3 | 4 | [token] 5 | # 网易云音乐账号(手机号/网易邮箱) 6 | account = 7 | 8 | # 密码,明文/MD5,建议自己去MD5在线加密网站给密码加密,然后填到下面 9 | # 明文例如:123456abcd 10 | # MD5例如:efa224f8de55cb668cd01edbcc***** 11 | password = e8c91842825e02523fd96502***** 12 | 13 | 14 | [setting] 15 | # 开关的选项只有 True 和 False 16 | # 打卡网站的网址,如果失效请提issue:https://github.com/ZainCheung/netease-cloud-api/issues/new 17 | api = https://api.wxiou.cn/api/wyapi/ 18 | 19 | # 密码是否需要MD5加密,如果是明文密码一定要打开 20 | # true 需要, 则直接将你的密码(明文)填入password,程序会替你进行加密 21 | # false 不需要, 那就自己计算出密码的MD5,然后填入上面的password内 22 | md5Switch = false 23 | 24 | # 是否开启多账号功能,如果打开将会忽视配置文件里的账号而从account.json中寻找账号信息 25 | # 如果选择使用多账号,请配置好account里的账号和密码,即account和password,而sckey不是必需的,如果为空则不会进行微信推送 26 | # 介于账号安全着想,account.json中的密码必须填写md5加密过的,请不要向他人透露自己的明文密码 27 | peopleSwitch = false 28 | 29 | # Server酱的密匙,不需要推送就留空,密匙的免费申请参考:http://sc.ftqq.com/ 30 | sckey = ***** 31 | -------------------------------------------------------------------------------- /腾讯视频签到/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "serverless-cloud-function-application": { 3 | "application":{ 4 | "Chinese":{ 5 | "name": "helloworld", 6 | "description": "helloworld 空白模板函数", 7 | "attention": "无", 8 | "readme": { 9 | "file": "", 10 | "content": "" 11 | }, 12 | "license": { 13 | "file": "", 14 | "content": "公开" 15 | }, 16 | "author": { 17 | "name": "腾讯云无服务器云函数团队" 18 | } 19 | }, 20 | "English":{ 21 | "name": "helloworld", 22 | "description": "This is helloworld function", 23 | "attention": "No", 24 | "readme": { 25 | "file": "", // readme file 26 | "content": "" //content of readme 27 | }, 28 | "license": { 29 | "file": "", // license file 30 | "content": "Open" //content of license 31 | }, 32 | "author": { 33 | "name": "Tencent Cloud Serverless Team" // author 34 | } 35 | }, 36 | "input_parameters":{ 37 | }, 38 | "output_parameters":{ 39 | }, 40 | "download_address":"https://github.com/tencentyun/scf-demo-repo/tree/master/Python2.7-helloworld", // Demo's git download url. demo的git下载链接 41 | "tags":[ 42 | "Python2.7", "helloworld" 43 | // The tags only support English and can be multiple, we suggest you to use keywords such as runtime, trigger, environment and so on. 44 | // 标签统一为英文,可编写多个,建议使用runtime、触发器、场景等关键字,用户可以通过该关键字搜索。前台需要展示,请认真填写,不支持中文 45 | ], 46 | "version": "1.0.6" 47 | // Version number, which identifies the demo version status. 48 | // Demo will not to update to the page if the version number unmodified. 49 | //版本号,通过版本号标识 demo 升级情况,未修改版本号会导致 demo 不更新至页面 50 | }, 51 | "functions": { 52 | "name": "helloworld", // Function name which only be in English. 函数名称,只支持英文 53 | "description": "helloworld blank template function. Helloworld 空白模板函数", 54 | "handler":"index.main_handler", 55 | "memorySize": 128, // Running memory. 运行配置内存 56 | "timeout": 3, // Running timeout. 运行超时时间 57 | "runtime": "Python2.7", // Runtime which users can search demo by this keyword. 运行环境,用户可以通过该关键字搜索["Python2.7", "Python3.6", "Nodejs6.10", "Java8", "LuaCDN", "NodejsCDN", "Php5", "Php7", "Nodejs8.9", "Go1"] 58 | "Environment":{ 59 | }, // Optional, used to define environment variables. 可选,用于定义环境变量 60 | "Events":{ 61 | }, // Optional, used define the event source that triggers this function. 可选,用于定义触发此函数的事件源 62 | "VpcConfig":{ 63 | }, // Optional, used configure cloud function's private network. 可选, 用于配置云函数访问 VPC 私有网络。 64 | "codeObject": { 65 | "codeFile": [ 66 | "index.py" 67 | ], 68 | "CodeUri":[ // Code download url which should be same as 'download_address'. 代码下载地址,和download_address保持一致 69 | "https://github.com/tencentyun/scf-demo-repo/tree/master/Python2.7-helloworld" 70 | ] 71 | } 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /腾讯视频签到/demo.json: -------------------------------------------------------------------------------- 1 | { 2 | "serverless-cloud-function-application": { 3 | "application":{ 4 | "Chinese":{ 5 | "name": "helloworld", 6 | "description": "helloworld 空白模板函数", 7 | "attention": "无", 8 | "readme": { 9 | "file": "", 10 | "content": "" 11 | }, 12 | "license": { 13 | "file": "", 14 | "content": "公开" 15 | }, 16 | "author": { 17 | "name": "腾讯云无服务器云函数团队" 18 | } 19 | }, 20 | "English":{ 21 | "name": "helloworld", 22 | "description": "This is helloworld function", 23 | "attention": "No", 24 | "readme": { 25 | "file": "", // readme file 26 | "content": "" //content of readme 27 | }, 28 | "license": { 29 | "file": "", // license file 30 | "content": "Open" //content of license 31 | }, 32 | "author": { 33 | "name": "Tencent Cloud Serverless Team" // author 34 | } 35 | }, 36 | "input_parameters":{ 37 | }, 38 | "output_parameters":{ 39 | }, 40 | "download_address":"https://github.com/tencentyun/scf-demo-repo/tree/master/Python2.7-helloworld", // github download address 41 | "tags":[ 42 | "Python2.7", "helloworld" 43 | // The labels are unified into English and can be written multiple. 44 | // It is recommended to use keywords such as runtime, trigger, and scene. Users can search by this keywords. 45 | // The labels need to be displayed, please fill in carefully. 46 | //标签统一为英文,可编写多个,建议使用runtime、触发器、场景等关键字,用户可以通过该关键字搜索。前台需要展示,请认真填写,不支持中文 47 | ], 48 | "version": "1.0.6" 49 | // Version number, which identifies the demo version status. 50 | // Demo will not to update to the page if the version number unmodified. 51 | // 版本号,通过版本号标识 demo 升级情况,未修改版本号会导致 demo 不更新至页面 52 | }, 53 | "functions": { 54 | "name": "helloworld", // Function name which only be in English. 函数名称,只支持英文 55 | "description": "helloworld blank template function 空白模板函数", 56 | "handler":"index.main_handler", 57 | "memorySize": 128, // Running memory. 运行配置内存 58 | "timeout": 3, // Running timeout. 运行超时时间 59 | "runtime": "Python2.7", //Runtime which users can search demo by this keyword. 运行环境,用户可以通过该关键字搜索["Python2.7", "Python3.6", "Nodejs6.10", "Java8", "LuaCDN", "NodejsCDN", "Php5", "Php7", "Nodejs8.9", "Go1"] 60 | "Environment":{ 61 | }, // Optional to define environment variables. 可选,用于定义环境变量 62 | "Events":{ 63 | }, // Optional to define the event source that triggers this function. 可选,用于定义触发此函数的事件源 64 | "VpcConfig":{ 65 | }, // Optional to configure cloud function's private network. 可选, 用于配置云函数访问 VPC 私有网络。 66 | "codeObject": { 67 | "codeFile": [ 68 | "index.py" 69 | ], 70 | "CodeUri":[ // Code download address which is same as 'download_address'. 代码下载地址,和 download_address 保持一致 71 | "https://github.com/tencentyun/scf-demo-repo/tree/master/Python2.7-helloworld" 72 | ] 73 | } 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /腾讯视频签到/index.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | ''' 3 | @author: sy-records 4 | @license: https://github.com/sy-records/v-checkin/blob/master/LICENSE 5 | @contact: 52o@qq52o.cn 6 | @desc: 腾讯视频好莱坞会员V力值签到,支持两次签到:一次正常签到,一次手机签到。 7 | @blog: https://qq52o.me 8 | ''' 9 | 10 | import sys 11 | reload(sys) 12 | sys.setdefaultencoding('utf-8') 13 | import requests 14 | 15 | auth_refresh_url = 'https://access.video.qq.com/user/auth_refresh?vappid=11059694&vsecret=fdf61a6be0aad57132bc5cdf78ac30145b6cd2c1470b0cfe&type=qq&g_tk=436137217&g_vstk=1103305739&g_actk=1233618242&callback=jQuery19107078619711839995_1596257528721&_=1596257528722' 16 | sckey = 'SCU107437T845b42e2ad9cd989053b83d77bdf64e85f1fabb4cc842' 17 | 18 | 19 | ftqq_url = "https://sc.ftqq.com/%s.send"%(sckey) 20 | url1 = 'https://vip.video.qq.com/fcgi-bin/comm_cgi?name=hierarchical_task_system&cmd=2' 21 | url2 = 'https://v.qq.com/x/bu/mobile_checkin' 22 | 23 | login_headers = { 24 | 'Referer': 'https://v.qq.com', 25 | 'Cookie': 'pgv_pvi=6428140544; RK=VJ5QDBTi6z; ptcz=5d8ebf03fd2e31b8d366148ba5ade33a6ddbf9198d7df99b9ae627a4e7efc6be; tvfe_boss_uuid=c4686e3a97ba60f2; video_guid=ac235aeb387f37d7; video_platform=2; pgv_pvid=6710598928; main_login=qq; vqq_access_token=395B903E37FB32B9BC8E4D90937EBD2D; vqq_appid=101483052; vqq_openid=480311F122A6383EE0A38475A0B0B486; vqq_vuserid=171165010; vqq_refresh_token=116C6E3473E5BD5655393E13C2961605; uin=o2440229611; pgv_info=ssid=s6998905652; skey=@OB0v8MMBQ; vqq_vusession=XFu68M-ifNbvTtuzppX1cw..; o_cookie=2440229611; uid=228756450; pgv_si=s6600956928; _qpsvr_localtk=0.00432450409112195; vqq_next_refresh_time=6227; vqq_login_time_init=1596256906; login_time_last=2020-8-1 12:41:48' 26 | } 27 | 28 | login = requests.get(auth_refresh_url, headers=login_headers) 29 | cookie = requests.utils.dict_from_cookiejar(login.cookies) 30 | 31 | if not cookie: 32 | print ("auth_refresh error") 33 | payload = {'text': '腾讯视频V力值签到通知', 'desp': '获取Cookie失败,Cookie失效'} 34 | requests.post(ftqq_url, params=payload) 35 | 36 | sign_headers = { 37 | 'Cookie': 'pgv_pvi=6428140544; RK=VJ5QDBTi6z; ptcz=5d8ebf03fd2e31b8d366148ba5ade33a6ddbf9198d7df99b9ae627a4e7efc6be; tvfe_boss_uuid=c4686e3a97ba60f2; video_guid=ac235aeb387f37d7; video_platform=2; pgv_pvid=6710598928; main_login=qq; vqq_access_token=395B903E37FB32B9BC8E4D90937EBD2D; vqq_appid=101483052; vqq_openid=480311F122A6383EE0A38475A0B0B486; vqq_vuserid=171165010; vqq_refresh_token=116C6E3473E5BD5655393E13C2961605; uin=o2440229611; pgv_info=ssid=s6998905652; skey=@OB0v8MMBQ; o_cookie=2440229611; uid=228756450; pgv_si=s6600956928; _qpsvr_localtk=0.00432450409112195; vqq_next_refresh_time=6227; vqq_login_time_init=1596256906; login_time_last=2020-8-1 12:41:48; vqq_vusession=' + cookie['vqq_vusession'] + ';', 38 | 'Referer': 'https://m.v.qq.com' 39 | } 40 | def start(): 41 | sign1 = requests.get(url1,headers=sign_headers).text 42 | if 'Account Verify Error' in sign1: 43 | print ('Sign1 error,Cookie Invalid') 44 | status = "链接1 失败,Cookie失效" 45 | else: 46 | print ('Sign1 Success') 47 | status = "链接1 成功,获得V力值:" + sign1[42:-14] 48 | 49 | sign2 = requests.get(url2,headers=sign_headers).text 50 | if 'Unauthorized' in sign2: 51 | print ('Sign2 error,Cookie Invalid') 52 | status = status + "\n\n 链接2 失败,Cookie失效" 53 | else: 54 | print ('Sign2 Success') 55 | status = status + "\n\n 链接2 成功" 56 | 57 | payload = {'text': '腾讯视频V力值签到通知', 'desp': status} 58 | requests.post(ftqq_url, params=payload) 59 | 60 | def main_handler(event, context): 61 | return start() 62 | if __name__ == '__main__': 63 | start() -------------------------------------------------------------------------------- /腾讯视频签到/template.yaml: -------------------------------------------------------------------------------- 1 | Resources: 2 | default: 3 | HowToUploadDemo: 4 | Properties: 5 | CodeUri: . 6 | Description: helloworld blank template functiion 空白模板函数 7 | Environment: 8 | Variables: {} 9 | Events: {} 10 | Handler: index.main_handler 11 | MemorySize: 128 12 | Runtime: Python2.7 13 | Timeout: 3 14 | VpcConfig: 15 | SubnetId: '' 16 | VpcId: '' 17 | Type: TencentCloud::Serverless::Function 18 | Type: TencentCloud::Serverless::Namespace 19 | --------------------------------------------------------------------------------