2020-03-03 22:35:25 +00:00
|
|
|
"""passbook Crypto forms"""
|
2020-05-16 19:21:42 +00:00
|
|
|
from cryptography.hazmat.backends import default_backend
|
|
|
|
from cryptography.hazmat.primitives.serialization import load_pem_private_key
|
|
|
|
from cryptography.x509 import load_pem_x509_certificate
|
2020-03-03 22:35:25 +00:00
|
|
|
from django import forms
|
|
|
|
from django.utils.translation import gettext_lazy as _
|
|
|
|
|
|
|
|
from passbook.crypto.models import CertificateKeyPair
|
|
|
|
|
|
|
|
|
|
|
|
class CertificateKeyPairForm(forms.ModelForm):
|
|
|
|
"""CertificateKeyPair Form"""
|
|
|
|
|
2020-05-16 19:21:42 +00:00
|
|
|
def clean_certificate_data(self):
|
|
|
|
"""Verify that input is a valid PEM x509 Certificate"""
|
|
|
|
certificate_data = self.cleaned_data["certificate_data"]
|
|
|
|
try:
|
|
|
|
load_pem_x509_certificate(
|
|
|
|
certificate_data.encode("utf-8"), default_backend()
|
|
|
|
)
|
|
|
|
except ValueError:
|
|
|
|
raise forms.ValidationError("Unable to load certificate.")
|
2020-05-20 14:10:12 +00:00
|
|
|
return certificate_data
|
2020-05-16 19:21:42 +00:00
|
|
|
|
|
|
|
def clean_key_data(self):
|
|
|
|
"""Verify that input is a valid PEM RSA Key"""
|
|
|
|
key_data = self.cleaned_data["key_data"]
|
|
|
|
# Since this field is optional, data can be empty.
|
|
|
|
if key_data == "":
|
2020-05-20 14:10:12 +00:00
|
|
|
return key_data
|
2020-05-16 19:21:42 +00:00
|
|
|
try:
|
|
|
|
load_pem_private_key(
|
|
|
|
str.encode("\n".join([x.strip() for x in key_data.split("\n")])),
|
|
|
|
password=None,
|
|
|
|
backend=default_backend(),
|
|
|
|
)
|
|
|
|
except ValueError:
|
|
|
|
raise forms.ValidationError("Unable to load private key.")
|
2020-05-20 14:10:12 +00:00
|
|
|
return key_data
|
2020-05-16 19:21:42 +00:00
|
|
|
|
2020-03-03 22:35:25 +00:00
|
|
|
class Meta:
|
|
|
|
|
|
|
|
model = CertificateKeyPair
|
|
|
|
fields = [
|
|
|
|
"name",
|
|
|
|
"certificate_data",
|
|
|
|
"key_data",
|
|
|
|
]
|
|
|
|
widgets = {
|
|
|
|
"name": forms.TextInput(),
|
|
|
|
"certificate_data": forms.Textarea(attrs={"class": "monospaced"}),
|
|
|
|
"key_data": forms.Textarea(attrs={"class": "monospaced"}),
|
|
|
|
}
|
|
|
|
labels = {
|
|
|
|
"certificate_data": _("Certificate"),
|
|
|
|
"key_data": _("Private Key"),
|
|
|
|
}
|