from django.core.management.base import BaseCommand, CommandError from pwdb.models import SharedPassword, IV_LENGTH import secrets class Command(BaseCommand): help = "Re-encrypts all the shared passwords after a secret key rollover" def add_arguments(self, parser): parser.add_argument("old_key", type=str) def handle(self, *args, **options): self.stdout.write("Re-encrypting passwords with the new secret key.") self.old_key = options["old_key"] try: for p in SharedPassword.objects.all(): self.update_password(p) self.stdout.write("Done.") except ValueError: self.stderr.write("Invalid key.") def update_password(self, password): clear_password = password.decrypt_password(key=self.old_key) password.iv = secrets.token_bytes(IV_LENGTH) password.set_password(clear_password) password.save()