File size: 6,132 Bytes
fcd4d46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
from unittest import result
from pdfplumber import pdf
import streamlit as st
import requests
from crypto import encrypt_pdf, decrypt_pdf
import os
import time
import json, asyncio
from transformers import pipeline

api_keys = {}
with open('api_keys.json', 'r') as file:
    api_keys = json.load(file)

PINATA_API_KEY = api_keys['PINATA_API_KEY']
PINATA_SECRET_API_KEY = api_keys['PINATA_SECRET_API_KEY']
PINATA_API_URL = "https://api.pinata.cloud/pinning/pinFileToIPFS"
IPFS_GATEWAY = "https://gateway.pinata.cloud/ipfs/"

with open("university_keys.json", "r") as f:
    UNIVERSITY_KEYS = json.load(f)

@st.cache_resource  
def load_ai_checker():  
    return  pipeline("text-generation", model="distilgpt2")

ai_checker = load_ai_checker()

def run_ai_check(pdf_text):
    prompt = "Does this certificate look fake? Answer with 'Yes' or 'No': " + pdf_text[:500]
    result = ai_checker(prompt, max_length=512, do_sample=False)[0]['generated_text']
    print(result, "AI Check \n")
    return "No" in result

def upload_to_ipfs(file_bytes, filename):
    headers = {
        "pinata_api_key": PINATA_API_KEY,
        "pinata_secret_api_key": PINATA_SECRET_API_KEY
    }
    files = {"file": (filename, file_bytes, "application/pdf")}
    response = requests.post(PINATA_API_URL, headers=headers, files=files)
    if response.status_code == 200:
        return response.json().get("IpfsHash")
    return None

if __name__ == "__main__":
    st.title("πŸŽ“ Certificate Verification System")
    tabs = ["Sign Certificate", "Encrypt Certificate", "Verify Certificate", "Decrypt Certificate"]
    choice = st.sidebar.radio("Select Action", tabs)

    if choice == "Sign Certificate":
        st.header("Sign & Encrypt Certificate")
        university = st.selectbox("Select University", list(UNIVERSITY_KEYS.keys()))
        pdf_file = st.file_uploader("Upload Certificate PDF", type=["pdf"])
        sign_button = st.button("Sign and Encrypt Certificate")
        
        if pdf_file and university and sign_button:
            pdf_bytes = pdf_file.read()
            # AI Check
            ai_check_passed = run_ai_check(pdf_bytes.decode(errors='ignore'))
            if not ai_check_passed:
                st.error("❌ AI Check Failed: Fake or Invalid Certificate Detected!")
            else:
                encrypted_pdf = encrypt_pdf(pdf_bytes, UNIVERSITY_KEYS[university].encode())
                filename = f"{university.replace(' ', '_')}_{time.time()}_signed_and_encrypted.pdf"
                ipfs_hash = upload_to_ipfs(encrypted_pdf, filename)
                if ipfs_hash:
                    st.success(f"βœ… Certificate Signed & Stored on IPFS! URL: {IPFS_GATEWAY}{ipfs_hash}")
                    st.download_button("Download Signed Certificate", encrypted_pdf, filename)
                else:
                    st.error("Failed to upload encrypted certificate to IPFS.")
    elif choice == "Encrypt Certificate":
        st.header("Encrypt Certificate")
        university = st.selectbox("Select University", list(UNIVERSITY_KEYS.keys()))
        pdf_file = st.file_uploader("Upload Certificate PDF", type=["pdf"])
        encrypt_button = st.button("Encrypt Certificate")

        if pdf_file and university and encrypt_button:
            pdf_bytes = pdf_file.read()
            encrypted_pdf = encrypt_pdf(pdf_bytes, UNIVERSITY_KEYS[university].encode())
            filename = f"{university.replace(' ', '_')}_encrypted.pdf"
            st.success("βœ… Certificate Encrypted Successfully!")
            st.download_button("Download Encrypted Certificate", encrypted_pdf, filename)

    elif choice == "Verify Certificate":
        st.header("Verify Certificate")
        university = st.selectbox("Select University", list(UNIVERSITY_KEYS.keys()))
        ipfs_hash = st.text_input("Enter IPFS Hash of the Signed Certificate")
        user_pdf_file = st.file_uploader("Upload Signed and Encrypted Certificate PDF", type=["pdf"])
        _verify_button = st.button("Verify Certificate")

        if ipfs_hash and university and _verify_button and user_pdf_file:
            response = requests.get(f"{IPFS_GATEWAY}{ipfs_hash}")
            if response.status_code == 200:
                encrypted_pdf = response.content
                try:
                    user_pdf_file = user_pdf_file.read()
                    print("I am working")
                    if encrypted_pdf != user_pdf_file:
                        st.error("❌ Verification Failed! Encrypted PDF does not match the IPFS Hash.")
                        st.stop()
                    decrypted_pdf = decrypt_pdf(encrypted_pdf, UNIVERSITY_KEYS[university].encode())
                    st.success("Certificate Verified Successfully and Valid βœ…")
                    st.download_button("Download Decrypted Certificate", decrypted_pdf, "decrypted_certificate.pdf")
                except:
                    st.error("❌ Verification Failed! Wrong University Selected.")
            else:
                st.error("Invalid IPFS Hash or file not found.")
    elif choice == "Decrypt Certificate":
        st.header("Decrypt Certificate")
        university = st.selectbox("Select University", list(UNIVERSITY_KEYS.keys()))
        pdf_file = st.file_uploader("Upload Encrypted Certificate PDF", type=["pdf"])
        decrypt_button = st.button("Decrypt Certificate")

        if pdf_file and university and decrypt_button:
            pdf_bytes = pdf_file.read()
            try:
                decrypted_pdf = decrypt_pdf(pdf_bytes, UNIVERSITY_KEYS[university].encode())
                st.success("βœ… Certificate Decrypted Successfully!")
                st.download_button("Download Decrypted Certificate", decrypted_pdf, "decrypted_certificate.pdf")
            except:
                st.error("❌ Decryption Failed! Wrong University Selected.")

    # Footer
    st.markdown("---")
    st.markdown("πŸ“Œ **Built by:**")
    st.text(f"Led By: Dr. M. Asha Kiran")
    st.text(f"Developer: Gajja Aarthi Goud")
    st.text(f"Roll Number: 23MC201A34")
    st.text(f"Department: MCA, IT Department, Anurag University")
    # st.run()