Decrypt ragnar.db.enc to ragnar.db. Keeps encrypted copy as backup.
(self)
| 773 | code_wrapped_key = self._wrap_fernet_key(fernet_key, code_wrapping) |
| 774 | cursor.execute(""" |
| 775 | INSERT INTO recovery_codes (code_hash, code_salt, encrypted_fernet_key) |
| 776 | VALUES (?, ?, ?) |
| 777 | """, (code_hash, code_salt, code_wrapped_key)) |
| 778 | |
| 779 | conn.commit() |
| 780 | |
| 781 | logger.info("Recovery codes regenerated") |
| 782 | return { |
| 783 | 'success': True, |
| 784 | 'recovery_codes': recovery_codes, |
| 785 | 'message': 'New recovery codes generated. Save them securely!' |
| 786 | } |
| 787 | |
| 788 | except Exception as e: |
| 789 | logger.error(f"Recovery code regeneration failed: {e}") |
| 790 | return {'success': False, 'error': str(e)} |
| 791 | |
| 792 | # ========================================================================= |
| 793 | # DATABASE ENCRYPTION / DECRYPTION |
| 794 | # ========================================================================= |
| 795 | |
| 796 | def encrypt_database(self): |
| 797 | """Encrypt ragnar.db to ragnar.db.enc and remove the plaintext copy.""" |
| 798 | if not self._fernet_key: |
| 799 | raise RuntimeError("No Fernet key available for encryption") |
| 800 | |
| 801 | if not os.path.exists(self.main_db_path): |
| 802 | logger.warning("No database to encrypt") |
| 803 | return |
| 804 | |
| 805 | with self._lock: |
| 806 | try: |
| 807 | f = Fernet(self._fernet_key) |
| 808 | with open(self.main_db_path, 'rb') as db_file: |
| 809 | plaintext = db_file.read() |
| 810 | |
| 811 | encrypted = f.encrypt(plaintext) |
| 812 |