## OpenCA - Command
## (c) 1998-2001 by Massimiliano Pala and OpenCA Group
##
##   File Name: changePasswd
##       Brief: change the passphrase of the keypair
##     Version: $Revision: 1.8 $
## Description: change the passphrase of the keypair if the key
##              is stored in the database
##  Parameters: 

require "$common_libs/csr-utils.lib";
 
sub cmdChangePasswd {

	my $formFile        = getRequired('ChangePasswdForm');

	## Check FORM : try to identify if the form has already been
	## completed and needs confirmation or if we are in the earlier
	## status ( checking for the correct parameters )

	## Status of FORM, possible values (in this order):
	my $KEY         = $query->param('key');
	my $PASSWD	= $query->param('passwd1');
	my $PASSWD2	= $query->param('passwd2');
	my $PASSWD3	= $query->param('passwd3');

	## check for the old passphrase or is it a new change?
	if (not $PASSWD) {
		printFormOne ( FILENAME => $formFile, KEY => $KEY );
		return 1;
	}

	## check the keys
	if ("$PASSWD3" ne "$PASSWD2") {
		generalError (gettext ("Two different new passphrases inserted. Please go <B><I>back</I></B> and correct the error."),
			560 );
	}
	
	## load cert with key
	my $cert = $db->getItem ( DATATYPE => "CERTIFICATE", KEY => $KEY);
	if ( not $cert ) {
		generalError (gettext ("Cannot load certificate from database!"));
	}

	my $key = $cert->getParsed()->{KEY};
	if ( not $key ) {
		generalError (gettext ("Cannot extract key from certificate!"));
	}

	## change passphrase
	my $new_key = $cryptoShell->dataConvert (
			DATATYPE  => "KEY",
			INFORM    => "PEM",
			OUTFORM   => "PKCS8",
			INPASSWD  => $PASSWD,
			OUTPASSWD => $PASSWD2,
			DATA      => $key );
	if ( not $new_key ) {
		generalError (gettext ("Cannot change passphrase of key!"));
	}

	## build new cert
	my $new_cert = new OpenCA::X509 ( SHELL => $cryptoShell,
					DATA => $cert->getPEMHeader ().
						$cert->getPEM ().
						$new_key );
	if ( not $new_cert ) {
		generalError (gettext ("Cannot create certificate with changed key!"));
	}

	## store cert with key
	if (not $db->storeItem ( DATATYPE => "CERTIFICATE", OBJECT => $new_cert, MODE => "UPDATE" )) {

		## the command one line before can only be done correct by OpenCA::DBI but not by OpenCA::DB
		if (not $db->storeItem ( DATATYPE => "VALID_CERTIFICATE", OBJECT => $new_cert, MODE => "UPDATE" )) {
			generalError (gettext ("Cannot store changed certificate and key in the database!").
			              "<br>".$db->errval(), $db->errno());
		}

	}

	## Send Success Page
	success (gettext ("Passphrase of the key was successfully changed."));

}

1;
