I'm doing a project where I have to generate a digital certificate and then add that certificate to pdf files. The key pair generation process is done on a mobile (written in with flutter) and I (correct me if I'm wrong) thnk that I would then have to send a csr or a the public key to a server to generate a certificate.
The problems that I am currently stuck with is what the whole process should look like? Do I generate a CSR on the mobile side, then send that csr file to the server that I created which has a python script to generate a certificate?
However, from the code I got from online for generating certificates, it seems like it requires the user's private key. How do I approach this problem? Here is the code I got which I can't remember where I got it.
Note: I already am able to generate a digital certificate (signing a hash)
from OpenSSL import crypto
import os
import sys
import datetime
import whois
dir_path = os.path.dirname(os.path.realpath(__file__))
if getattr(sys, 'frozen', False):
dir_path = os.path.dirname(sys.executable)
elif __file__:
dir_path = os.path.dirname(__file__)
currentDir = dir_path.replace('\\', '/')
#Variables
TYPE_RSA = crypto.TYPE_RSA
TYPE_DSA = crypto.TYPE_DSA
HOME = currentDir
now = datetime.datetime.now()
d = now.date()
#Pull these out of scope
cn = input("Enter the Domain: ")
key = crypto.PKey()
keypath = HOME + "/" + cn + '-' + str(d) + '.key'
csrpath = HOME + "/" + cn + '-' + str(d) + '.csr'
crtpath = HOME + "/" + cn + '-' + str(d) + '.crt'
#Generate the key
def generatekey():
if os.path.exists(keypath):
print ("Certificate file exists, aborting.")
print (keypath)
sys.exit(1)
#Else write the key to the keyfile
else:
print("Generating Key Please standby")
key.generate_key(TYPE_RSA, 4096)
f = open(keypath, "wb")
f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key))
f.close()
#return key
generatekey()
#Generate CSR
def generatecsr():
print ("How would you like to generate csr data?\n" \
"1) CQB (For Self-Signed Certs).\n" \
"2) Specify your own.\n" \
"3) Attempt Whois Look")
option = int(input("Choose (1/2/3): "))
if option == 1:
c = 'US'
st = 'California'
l = 'Berkley'
o = 'CQB'
ou = 'Network Operations'
elif option == 2:
c = input('Enter your country(ex. US): ')
st = input("Enter your state(ex. Nevada): ")
l = input("Enter your location(City): ")
o = input("Enter your organization: ")
ou = input("Enter your organizational unit(ex. IT): ")
else:
print("Attempting WHOIS Lookup")
w = whois.whois(cn)
c = str(w.get('country'))
st = str(w.get('state')).lower().title()
l = str(w.get('city')).lower().title()
o = str(w.get('org')).lower().title()
ou = 'Network Operations'
req = crypto.X509Req()
req.get_subject().CN = cn
req.get_subject().C = c
req.get_subject().ST = st
req.get_subject().L = l
req.get_subject().O = o
req.get_subject().OU = ou
req.set_pubkey(key)
req.sign(key, "sha256")
if os.path.exists(csrpath):
print ("Certificate File Exists, aborting.")
print(csrpath)
else:
f = open(csrpath, "wb")
f.write(crypto.dump_certificate_request(crypto.FILETYPE_PEM, req))
f.close()
print("Success")
#Generate the certificate
reply = str(input('Is this a Self-Signed Cert (y/n): ')).lower().strip()
if reply[0] == 'y':
cert = crypto.X509()
cert.get_subject().CN = cn
cert.get_subject().C = c
cert.get_subject().ST = st
cert.get_subject().L = l
cert.get_subject().O = o
cert.get_subject().OU = ou
cert.set_serial_number(1000)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(315360000)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(key)
cert.sign(key, "sha256")
if os.path.exists(crtpath):
print ("Certificate File Exists, aborting.")
print (crtpath)
else:
f = open(crtpath, "wb")
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
f.close()
print ("CRT Stored Here :" + crtpath)
generatecsr()
print ("Key Stored Here :" + keypath)
print ("CSR Stored Here :" + csrpath)
Related
Im currently working on a way that i can press tab and it switches trough folder in the directory but when I select a folder by using tab it should become the new directory.
import os
from cryptography.fernet import Fernet
import keyboard
# a = input("Pfad: ")
check = 0
while check == 0:
pfad = "C:/Users/Messing/Documents"
os.chdir(pfad)
filesl = []
for file in os.listdir():
if os.path.isdir(file) == True:
filesl.append(file)
shot_pressed1 = 0
was_pressed = False
while True:
if keyboard.is_pressed('tab'):
if not was_pressed:
shot_pressed1 += 1
shot_pressed = shot_pressed1 % len(filesl)
print("\r", str(os.getcwd()) + "\\" + str(filesl[shot_pressed]), end="")
was_pressed = True
if keyboard.is_pressed("enter"):
# print(filesl[shot_pressed], end="\n")
pfad = (pfad + "/" + filesl[shot_pressed])
# print("\n", pfad, end="")
# check += 1
break
else:
was_pressed = False
Thanks for any help.
The problem is that the path doesnt get updated I think.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 months ago.
Improve this question
This is the main part of the code that downloads files given Google Drive share links:
from googleapiclient.discovery import build
from google.auth.transport.requests import Request
from datetime import datetime
import os, time
def timestamp(date):
return time.mktime(date.timetuple())
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
files_dir = {}
def process(filename):
folder = ""
working_on = 0.0
total = 0
file = open(filename)
lines = file.readlines()
for l in lines:
if "folder" in l:
folderName = l.split("folder:")[1].split("]")[0].split("\n")[0]
if folderName not in files_dir:
files_dir[folderName] = []
folder = folderName
if "https" in l and "id" in l:
l = l.split("id=")[1].split("\n")[0]
files_dir[folder].append(l)
total = total + 1
# Creating directories
for key in files_dir:
if "None" not in key:
if not os.path.exists(key):
os.makedirs(key)
progress = "00.00"
print ("Google Drive Downloader v2.0\n")
print ("Files to download:", total)
print ("Starting downloads ...\n")
for key in files_dir:
for l in files_dir[key]:
file_id = l
try:
request = service.files().get_media(fileId=file_id)
data = service.files().get(fileId=l, fields='*').execute()
meta = service.files().get(fileId=l, fields="*", supportsTeamDrives=True).execute()
modtime = timestamp(datetime.strptime(meta["modifiedTime"], '%Y-%m-%dT%H:%M:%S.%fZ'))
print(" ")
print("meta", meta["modifiedTime"])
fname = key + "/" + data['name']
dodownload = not os.path.lexists(fname)
if not dodownload:
modtimeondisk = os.path.getmtime(fname)
dodownload = modtimeondisk <= modtime
if dodownload:
print("NEWER VERSION DETECTED")
#modtimesource = os.path.getmtime(fh)
#print("mod: ", modtimetarget, modtimesource)
if dodownload:# or modtimetarget < modtimesource:
if "None" not in key:
fh = io.FileIO(os.path.join(key, data['name']), 'wb')
else:
fh = io.FileIO(os.path.join(key.split("/")[0], data['name']), 'wb')
print("[" + progress + "%] " + "Downlading: " + data['name'])
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
os.utime(fname, (time.time(), modtime))
else:
print("[" + progress + "%] " + "Skipping: " + data['name'])
except Exception as e:
print(e)
working_on = working_on + 1
val = round(float((working_on / total) * 100), 2)
if val < 10:
progress = "0{:0.2f}".format(val)
else:
progress = "{:0.2f}".format(val)
Can this be improved? I see people calling other functions like downloadfile, etc from Google Drive API so not sure how they fare against MediaIoBaseDownload, etc.
import os
def delete(files):
os.system('del /f /s /q "%s\\*.*"' % files)
print("清理成功!")
users = os.path.expandvars('$HOMEPATH')
f = open(r'C:' + users + '\\AppData\\Roaming\\Tencent\\WeChat\\All Users\\config\\3ebffe94.ini')
if f.read() == 'MyDocument:':
location = 'C:' + users + '\Documents\WeChat Files'
else:
location = f.read() + "\WeChat Files"
list = os.listdir(location)
list.remove('All Users')
list.remove('Applet')
print("""
""")
print(list)
print("""
""")
while True:
temp = input("选择你要清理的微信号:")
try:
if 0<int(temp)<=len(list):
temp1 = int(temp) - 1
wxid = list[temp1]
break
else:
print("输入错误,请重新输入。")
except:
print("输入错误,请重新输入。")
print("""
-----------------------------Windows微信清理工具-------------------------------------
------------------------------【1.清理聊天记录】---------------------------------
-----------------------------【2.清理图片和视频】-----------------------------------
-----------------------------【3.清理接收到的文件】------------------------------
------------------------------【4.清理全部数据】-------------------------------
""")
while True:
choice = input("请输入要执行的操作所对应的代码:")
if choice == '1':
dialog = location + "\\" + wxid + '\Msg'
delete(dialog)
break
elif choice == '2':
pictures = location + "\\" + wxid + '\FileStorage\Image'
delete(pictures)
videos = location + "\\" + wxid + '\FileStorage\Video'
delete(videos)
break
elif choice == '3':
documents = location + "\\" + wxid + '\FileStorage\File'
delete(documents)
break
elif choice == '4':
delall = location + "\\" + wxid
delete(delall)
break
else:
print("输入错误,请重新输入。")
When it runs in D drive ,it works well.
But when it runs in other drives ,there is something wrong.
Traceback (most recent call last):
File "C:\Users\14932\Desktop\Windows微信清理工具.py", line 13, in <module>
list = os.listdir(location)
FileNotFoundError: [WinError 3] 系统找不到指定的路径。: '\\WeChat Files'
Access the result of variables:
>>> f
<_io.TextIOWrapper name='C:\\Users\\14932\\AppData\\Roaming\\Tencent\\WeChat\\All Users\\config\\3ebffe94.ini' mode='r' encoding='cp936'>
>>> f.read()
''
I packed an exe file on another computer and put it on my computer to work properly.
What is wrong with it?
Could you help me?
I do not know how to fix the bug.
I asked other bbs,did not find the best ways.
I believe the problem is here:
if f.read() == 'MyDocument:':
location = 'C:' + users + '\Documents\WeChat Files'
else:
location = f.read() + "\WeChat Files"
The first call to f.read() reads the entire contents of the file. There is nothing left to read on the second call, so it returns a blank string.
I'm trying to download a export of space in a zip file. But somehow python downloads a empty and corrupted zip file. When you download the file manual by the browser everything is ok.
I use Python 2.7.13
#!/usr/bin/python
import xmlrpclib
import time
import urllib
confluencesite = "https://confluence.com"
server = xmlrpclib.ServerProxy(confluencesite + '/rpc/xmlrpc')
username = '*'
password = '*'
token = server.confluence2.login(username, password)
loginString = "?os_username=" + username + "&os_password=" + password
filelist = ""
start = True
spacesummary = server.confluence2.getSpaces(token)
for space in spacesummary:
#if space['name'] == "24-codING":
# start = True
# continue
if start:
if space['type'] == 'global':
print "Exporting space " + space['name']
spaceDownloadUrl = server.confluence2.exportSpace(token, space['key'],
"TYPE_XML",
exportAll['true'])
filename = spaceDownloadUrl.split('/')[-1].split('#')[0].split('?')[0]
time.sleep(0.5)
urllib.urlretrieve(spaceDownloadUrl + loginString, filename)
print filename + " saved."
f = open("exportedspaces.txt", 'a')
f.write(filename + "\n")
f.close()
It's solved by the answer of Coldspeed. Changing the following:
loginString = "?os_username=" + username + "&os_password=" + password
to
loginString = "?os_username=" + username + "&os_password=" + password
I have written the following code and can't get it working and I can't see why. The code:
Reads list of target files
Loops through the directories
Runs MD5 hash on the file
Checks the activefile for previous md5 hashes for said file
If the file is new it will log it as new
If the log is existing but changed it will write the change and log the change
If not new and no change then do nothing
Here is the code:
import hashlib
import logging as log
import optparse
import os
import re
import sys
import glob
import shutil
def md5(fileName):
"""Compute md5 hash of the specified file"""
try:
fileHandle = open(fileName, "rb")
except IOError:
return
m5Hash = hashlib.md5()
while True:
data = fileHandle.read(8192)
if not data:
break
m5Hash.update(data)
fileHandle.close()
return m5Hash.hexdigest()
req = open("requested.txt")
for reqline in req:
reqName = reqline[reqline.rfind('/') + 1:len(reqline) - 1]
reqDir = reqline[0:reqline.rfind('/') + 1]
tempFile = open("activetemp.txt", 'w')
for name in glob.glob(reqDir + reqName):
fileHash = md5(name)
actInt = 0
if fileHash != None:
actFile = open("activefile.txt")
for actLine in actFile:
actNameDir = actLine[0:actLine.rfind(' : ')]
actHash = actLine[actLine.rfind(' : ') + 3:len(actLine) -1]
if actNameDir == name and actHash == fileHash:
tempFile.write(name + " : " + fileHash + "\n")
actInt = 1
print fileHash
print actHash
print name
print actNameDir
if actNameDir == name and actHash != fileHash:
fimlog = open("fimlog.txt", 'a')
tempFile.write(name + " : " + actHash + "\n")
actInt = 1
fimlog.write("FIM Log: The file " + name + " was modified: " + actHash + "\n")
if actInt == 0:
fimlog = open("fimlog.txt", 'a')
fimlog.write("FIM Log: The file " + name + " was created: " + fileHash + "\n")
tempFile.write(name + " : " + fileHash + "\n")
shutil.copyfile("activetemp.txt", "activefile.txt")
You never really described the problem, but one possible culprit is that you never close the tempFile (or the other files for that matter), so the file copy at the end may fail.