from OpenSSL import crypto
from Crypto.PublicKey import RSA


def generate_self_signed_cert(cert_country, cert_state, cert_organization,
                              cert_locality, cert_organizational_unit,
                              cert_common_name, valid_days, serial_number):
  rsa_key = RSA.generate(2048)

  pk = crypto.load_privatekey(crypto.FILETYPE_PEM,
                              rsa_key.exportKey('PEM', pkcs=1))
  cert = crypto.X509()
  sub = cert.get_subject()
  sub.CN = cert_common_name
  sub.C = cert_country
  sub.ST = cert_state
  sub.L = cert_locality
  sub.O = cert_organization

  # optional
  if cert_organizational_unit:
    sub.OU = cert_organizational_unit

  cert.set_serial_number(serial_number)
  cert.gmtime_adj_notBefore(0)
  cert.gmtime_adj_notAfter(valid_days * 24 * 60 * 60)  # Valid for a year
  cert.set_issuer(sub)
  cert.set_pubkey(pk)
  cert.sign(pk, 'sha1')

  cert_text = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
  priv_key_text = rsa_key.exportKey('PEM', pkcs=1)

  return str(cert_text), str(priv_key_text)


if __name__ == "__main__":
    test = generate_self_signed_cert(cert_country="DE", cert_state="Dresden", cert_organization="IchAG", cert_locality="Sachsen", cert_organizational_unit="mandan01", cert_common_name="mandan01", valid_days=365, serial_number=12)
    privatekey = test[1].rstrip("'").strip("b'")
    cert = test[0].rstrip("'").strip("b'")
    #print(privatekey)
    for key in privatekey.split("\\n"):
        with open("testkey", "a") as testcert:
            print(key, file=testcert)
    for cert_out in cert.split("\\n"):
        with open("testcert", "a") as testcert_out:
            print(cert_out, file=testcert_out)

    #test2 = "xccj\njdkjd\n"
    #print(test2)