function encrypt(inputFile, outputFile, key, mode) %Implements a random shift cipher % input: inputFile - the file to be encrypted or decrypted % input: outputFile - where the result of the operations are stored % input: key - the encryption key, can be any positive integer % input: mode - 0: encrypt, 1: decrypt % step 1: read the input data % step 2: compute the encrypted text % step 3: write the output data % open the input file [inputFID, message] = fopen(inputFile, 'r'); if inputFID==-1 %error fprintf(2,'Error, could not open the input file: %s\n', message); return; end [outputFID, message] = fopen(outputFile, 'w'); if outputFID==-1 %error fprintf(2, 'Error, could not open the output file: %s\n', message); fclose(inputFID); return; end % seed the pseudo-random number generator rng(key); data = fread(inputFID,1); while length(data)>0 % ASCII characters go between 0 and 127 offset = randi(128) - 1; % gives a random number between 0 and 127 if mode==0 %encrypt mode output = data + offset; else %decrypt mode output = data - offset; end % wrap-around if output > 127 output = output - 128; end if output < 0 output = output + 128; end fprintf(outputFID, '%c', output); data = fread(inputFID, 1); end fclose(inputFID); fclose(outputFID); end