// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy(CORS_ALLOW_ALL, builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); services.AddCors(options => { options.AddPolicy(CORS_ALLOW_SPECIFIC, builder => { builder.WithOrigins("http://localhost:4200"); }); }); services.AddSingleton <IFingerprintService, FingerprintService>(c => { // This port name is correct for Pi 3 and 4 running Raspian Buster string portName = "/dev/serial0"; // "/dev/ttyS0","/dev/ttyAMA0","/dev/serial1","/dev/serial0" Console.WriteLine($"Creating Fingerprint service (Serial {portName})"); var fps = new FingerprintService(); fps.Fingerprint.SerialPortName = portName; return(fps); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
private static int MAX_SIGNATURE_COUNT = 5; // the number of signatures to reduce to public Repository(IPermutations permutations, DatabaseService dbService, FingerprintService fingerprintService) { this.permutations = permutations; this.minHash = new MinHash(this.permutations); this.dbService = dbService; this.fingerprintService = fingerprintService; }
public IActionResult TriggerFingerprint() { // Description: Using for DEBUG. URL: https://lifeblocks.site/home/testfingerprintbutton ViewBag.DoctorName = HttpContext.Session.GetString(Globals.currentUserName); // Retrieve the Public IP of the Client Computer using the browser var ip = HttpContext.Connection.RemoteIpAddress; string ipAddress = ip.ToString(); bool debug = true; // true for DEBUG string status = "entered function"; TcpClient tcpClient = new TcpClient(); List <Image> fpList = FingerprintService.authenticateFP("24.84.225.22", 3); // Do fingerprint fetch from windows service here Image fpImg = null; for (int i = 0; i < fpList.Count; i++) { var debugByte = FingerprintService.imgToByte(fpList[i]); fpImg = FingerprintService.byteToImg(debugByte); fpImg.Save(i.ToString() + ".bmp"); } // Write the Public IP of the client computer on the window var model = new TestFingerprintButton() { message = status }; return(RedirectToAction("TestFingerprintButton", model)); }
public static void Init() { FingerprintService.InitFingerprint(new WindowsFingerprint()); // These loosely typed parameter lists are rather gross. Is there a cleaner way to do this? // params: channel, autoReconnect PlatformTypes.Register <IPipeClient>((arr) => new WindowsPipeClient((string)arr[0], (arr.Length > 1) ? (bool)arr[1] : false)); // params: channel PlatformTypes.Register <IPipeServer>((arr) => new WindowsPipeServer((string)arr[0])); PlatformTypes.Register <IGUIChecks>((arr) => new WindowsGUIChecks()); PlatformTypes.Register <IAntitampering>((arr) => new WindowsAntitampering()); PlatformTypes.Register <INetworkInfo>((arr) => new NetworkListUtil()); PlatformTypes.Register <IAuthenticationStorage>((arr) => new RegistryAuthenticationStorage()); PlatformTypes.Register <IPathProvider>((arr) => new WindowsPathProvider()); PlatformTypes.Register <IFilterAgent>((arr) => new WindowsFilterAgent()); PlatformTypes.Register <IFilterUpdater>((arr) => new WindowsFilterUpdater()); }
public void SetUp() { fingerprintDescriptor = new Mock<IFingerprintDescriptor>(MockBehavior.Strict); spectrumService = new Mock<ISpectrumService>(MockBehavior.Strict); waveletDecomposition = new Mock<IWaveletDecomposition>(MockBehavior.Strict); fingerprintService = new FingerprintService(spectrumService.Object, waveletDecomposition.Object, fingerprintDescriptor.Object); }
public void SetUp() { fingerprintDescriptor = new Mock <IFingerprintDescriptor>(MockBehavior.Strict); spectrumService = new Mock <ISpectrumService>(MockBehavior.Strict); waveletDecomposition = new Mock <IWaveletDecomposition>(MockBehavior.Strict); fingerprintService = new FingerprintService(spectrumService.Object, waveletDecomposition.Object, fingerprintDescriptor.Object); }
public void SetUp() { fingerprintDescriptor = new Mock <IFingerprintDescriptor>(MockBehavior.Strict); spectrumService = new Mock <ISpectrumService>(MockBehavior.Strict); waveletDecomposition = new Mock <IWaveletDecomposition>(MockBehavior.Strict); localitySensitiveHashingAlgorithm = new Mock <ILocalitySensitiveHashingAlgorithm>(MockBehavior.Strict); fingerprintService = new FingerprintService( spectrumService.Object, localitySensitiveHashingAlgorithm.Object, waveletDecomposition.Object, fingerprintDescriptor.Object); }
public void SetUp() { fingerprintDescriptor = new Mock <IFingerprintDescriptor>(MockBehavior.Strict); spectrumService = new Mock <ISpectrumService>(MockBehavior.Strict); waveletDecomposition = new Mock <IWaveletDecomposition>(MockBehavior.Strict); DependencyResolver.Current.Bind <IFingerprintDescriptor, IFingerprintDescriptor>( fingerprintDescriptor.Object); DependencyResolver.Current.Bind <ISpectrumService, ISpectrumService>(spectrumService.Object); DependencyResolver.Current.Bind <IWaveletDecomposition, IWaveletDecomposition>(waveletDecomposition.Object); fingerprintService = new FingerprintService(); }
public FindSimilarClientForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); // // Constructor code after the InitializeComponent() call. // this.version.Text = Mirage.Mir.VERSION; this.DistanceTypeCombo.DataSource = Enum.GetValues(typeof(AudioFeature.DistanceType)); this.ThresholdTablesCombo.DataSource = Enum.GetValues(typeof(ThresholdTables)); // Instansiate SCMS or Mandel Ellis Repository this.db = new Db(); // Instansiate Soundfingerprinting Repository FingerprintService fingerprintService = Analyzer.GetSoundfingerprintingService(); this.databaseService = DatabaseService.Instance; IPermutations permutations = new LocalPermutations("Soundfingerprinting\\perms.csv", ","); //IPermutations permutations = new LocalPermutations("Soundfingerprinting\\perms-new.csv", ","); repository = new Repository(permutations, databaseService, fingerprintService); if (rbScms.Checked) { IgnoreFileLengthCheckBox.Visible = true; DistanceTypeCombo.Visible = true; LessAccurateCheckBox.Visible = false; ThresholdTablesCombo.Visible = false; SearchAllFilesCheckbox.Visible = false; } else { IgnoreFileLengthCheckBox.Visible = false; DistanceTypeCombo.Visible = false; LessAccurateCheckBox.Visible = true; ThresholdTablesCombo.Visible = true; SearchAllFilesCheckbox.Visible = true; } ReadAllTracks(); }
public static void Init() { FingerprintService.InitFingerprint(new MacFingerprint()); PlatformTypes.Register <IPipeServer>((arr) => new SocketPipeServer()); // params: channel PlatformTypes.Register <IPipeClient>((arr) => new SocketPipeClient()); PlatformTypes.Register <IGUIChecks>((arr) => new MacGUIChecks()); PlatformTypes.Register <IAntitampering>((arr) => new MacAntitampering()); PlatformTypes.Register <INetworkInfo>((arr) => new MacNetworkInfo()); PlatformTypes.Register <IAuthenticationStorage>((arr) => new FileAuthenticationStorage()); PlatformTypes.Register <IPathProvider>((arr) => new MacPathProvider()); NativeLog.Init(); }
public void ShouldRunCorrectlyForSpecificUseCase() { int sequenceNumber = 334; float[] samples = GetAudioSamples().Samples; int start = sequenceNumber * 1536; float[] troubledPart = new float[8192 + 2048]; Array.Copy(samples, start, troubledPart, 0, 8192 + 2048); var audioSamples = new AudioSamples(troubledPart, "test", 5512); var fingerprintService = new FingerprintService( new SpectrumService(new LomontFFT(), new LogUtility()), new LocalitySensitiveHashingAlgorithm( new MinHashService(new DefaultPermutations()), new HashConverter()), new StandardHaarWaveletDecomposition(), new FingerprintDescriptor()); var fastFingerprintService = new FingerprintService( new SpectrumService(new LomontFFT(), new LogUtility()), new LocalitySensitiveHashingAlgorithm( new MinHashService(new DefaultPermutations()), new HashConverter()), new StandardHaarWaveletDecomposition(), new FastFingerprintDescriptor()); int runs = 10; for (int i = 0; i < runs; ++i) { var x = fingerprintService.CreateFingerprints(audioSamples, new DefaultFingerprintConfiguration()); var y = fastFingerprintService.CreateFingerprints(audioSamples, new DefaultFingerprintConfiguration()); for (int j = 0; j < x.Count; ++j) { CollectionAssert.AreEqual(x[j].HashBins, y[j].HashBins); } } }
public IActionResult RequestAccess(RequestAccessViewModel requestAccessViewModel) { // Description: Authenticates a patient's identity when a Doctor requests access to their medical information // Get's the Doctor's information for current session ViewBag.DoctorName = HttpContext.Session.GetString(Globals.currentUserName); if (!ModelState.IsValid) { return(View(requestAccessViewModel)); } string PHN = HttpContext.Session.GetString(Globals.currentPPHN); string patientSignPublicKey = HttpContext.Session.GetString(Globals.currentPSPubK); string doctorSignPrivatekey = HttpContext.Session.GetString(Globals.currentDSPriK); string doctorSignPublicKey = EncryptionService.getSignPublicKeyStringFromPrivate(doctorSignPrivatekey); string doctorAgreePrivatekey = HttpContext.Session.GetString(Globals.currentDAPriK); string doctorAgreePublicKey = EncryptionService.getAgreePublicKeyStringFromPrivate(doctorAgreePrivatekey); string keyword = requestAccessViewModel.keyword; // Searches for a patient with the specified PHN Assets <UserCredAssetData> userAsset = _bigChainDbService.GetUserAssetFromTypeID(AssetType.Patient, PHN); if (userAsset == null) { ModelState.AddModelError("", "Could not find a patient profile with PHN: " + PHN); return(View(requestAccessViewModel)); } // Decrypt the patient's fingerprint data stored in the Blockchain byte[] dbFpData = null; string patientSignPrivateKey, patientAgreePrivateKey; List <string> dbList = userAsset.data.Data.FingerprintData; List <Image> dbfpList = new List <Image>(); try { foreach (string db in dbList) { EncryptionService.decryptFingerprintData(PHN, keyword, db, out dbFpData); dbfpList.Add(FingerprintService.byteToImg(dbFpData)); } EncryptionService.getPrivateKeyFromIDKeyword(PHN, keyword, userAsset.data.Data.PrivateKeys, out patientSignPrivateKey, out patientAgreePrivateKey); } catch { ModelState.AddModelError("", "Keyword may be incorrect"); return(View(requestAccessViewModel)); } // Send request to the Client Computer to authenticate with fingerprint int numScans = 1; List <Image> fpList = FingerprintService.authenticateFP("24.84.225.22", numScans); // DEBUG: Jacob's Computer // Check if fingerprint data is valid if (fpList.Count < numScans) { ModelState.AddModelError("", "Something went wrong with the fingerprint scan, try again."); return(View(requestAccessViewModel)); } Image fpImg = fpList[0]; // Compare the scanned fingerprint with the one saved in the database if (!FingerprintService.compareFP(fpImg, dbfpList)) { ModelState.AddModelError("", "The fingerprint did not match, try again."); return(View(requestAccessViewModel)); } // Choose the types of records we want to get AssetType[] typeList = { AssetType.TestRequisition }; var recordList = _bigChainDbService.GetAllTypeRecordsFromPPublicKey <string> (typeList, patientSignPublicKey); foreach (var record in recordList) { MetaDataSaved <object> metadata = record.metadata; if (!metadata.AccessList.Keys.Contains(doctorSignPublicKey)) { var hashedKey = metadata.AccessList[patientSignPublicKey]; var dataDecryptionKey = EncryptionService.getDecryptedEncryptionKey(hashedKey, patientAgreePrivateKey); var newHash = EncryptionService.getEncryptedEncryptionKey(dataDecryptionKey, patientAgreePrivateKey, doctorAgreePublicKey); metadata.AccessList[doctorSignPublicKey] = newHash; _bigChainDbService.SendTransferTransactionToDataBase(record.id, metadata, patientSignPrivateKey, patientSignPublicKey, record.transID); } } return(RedirectToAction("PatientRecords")); }
public static void Main(string[] args) { Analyzer.AnalysisMethod analysisMethod = Analyzer.AnalysisMethod.SCMS; //Analyzer.AnalysisMethod analysisMethod = Analyzer.AnalysisMethod.MandelEllis; string scanPath = ""; double skipDurationAboveSeconds = -1; // less than zero disables this string queryPath = ""; int queryId = -1; int numToTake = 20; double percentage = 0.4; // percentage below and above when querying bool resetdb = false; bool silent = false; AudioFeature.DistanceType distanceType = AudioFeature.DistanceType.KullbackLeiblerDivergence; // Command line parsing Arguments CommandLine = new Arguments(args); if(CommandLine["match"] != null) { queryPath = CommandLine["match"]; } if(CommandLine["matchid"] != null) { string matchId = CommandLine["matchid"]; queryId = int.Parse(matchId); } if(CommandLine["scandir"] != null) { scanPath = CommandLine["scandir"]; } if(CommandLine["skipduration"] != null) { double.TryParse(CommandLine["skipduration"], NumberStyles.Number,CultureInfo.InvariantCulture, out skipDurationAboveSeconds); } if(CommandLine["num"] != null) { string num = CommandLine["num"]; numToTake = int.Parse(num); } if(CommandLine["percentage"] != null) { double.TryParse(CommandLine["percentage"], NumberStyles.Number,CultureInfo.InvariantCulture, out percentage); } if(CommandLine["type"] != null) { string type = CommandLine["type"]; if (type.Equals("kl", StringComparison.InvariantCultureIgnoreCase)) { distanceType = AudioFeature.DistanceType.KullbackLeiblerDivergence; } else if (type.StartsWith("dtw", StringComparison.InvariantCultureIgnoreCase)) { if (type.Equals("dtwe", StringComparison.InvariantCultureIgnoreCase)) { distanceType = AudioFeature.DistanceType.Dtw_Euclidean; } else if (type.Equals("dtwe2", StringComparison.InvariantCultureIgnoreCase)) { distanceType = AudioFeature.DistanceType.Dtw_SquaredEuclidean; } else if (type.Equals("dtwman", StringComparison.InvariantCultureIgnoreCase)) { distanceType = AudioFeature.DistanceType.Dtw_Manhattan; } else if (type.Equals("dtwmax", StringComparison.InvariantCultureIgnoreCase)) { distanceType = AudioFeature.DistanceType.Dtw_Maximum; } else if (type.Equals("ucrdtw", StringComparison.InvariantCultureIgnoreCase)) { distanceType = AudioFeature.DistanceType.UCR_Dtw; } else { distanceType = AudioFeature.DistanceType.Dtw_Euclidean; } } } if(CommandLine["dtw"] != null || CommandLine["dtwe"] != null) { distanceType = AudioFeature.DistanceType.Dtw_Euclidean; } if(CommandLine["dtwe2"] != null) { distanceType = AudioFeature.DistanceType.Dtw_SquaredEuclidean; } if(CommandLine["dtwman"] != null) { distanceType = AudioFeature.DistanceType.Dtw_Manhattan; } if(CommandLine["dtwmax"] != null) { distanceType = AudioFeature.DistanceType.Dtw_Maximum; } if(CommandLine["kl"] != null) { distanceType = AudioFeature.DistanceType.KullbackLeiblerDivergence; } if(CommandLine["ucrdtw"] != null) { distanceType = AudioFeature.DistanceType.UCR_Dtw; } if(CommandLine["resetdb"] != null) { resetdb = true; } if(CommandLine["silent"] != null) { silent = true; } if(CommandLine["permutations"] != null) { Console.WriteLine("Generating hash permutations for used by the Soundfingerprinting methods."); Console.WriteLine("Saving to file: {0}", "Soundfingerprinting\\perms-new.csv"); Console.WriteLine(); PermutationGeneratorService permutationGeneratorService = new PermutationGeneratorService(); Analyzer.GenerateAndSavePermutations(permutationGeneratorService, "Soundfingerprinting\\perms-new.csv"); return; } if(CommandLine["?"] != null) { PrintUsage(); return; } if(CommandLine["help"] != null) { PrintUsage(); return; } if(CommandLine["gui"] != null) { StartGUI(); return; } if (queryPath == "" && queryId == -1 && scanPath == "") { PrintUsage(); return; } // Get database Db mandelEllisScmsDatabase = new Db(); // For MandelEllis and SCMS // Instansiate soundfingerprinting Repository FingerprintService fingerprintService = Analyzer.GetSoundfingerprintingService(); DatabaseService databaseService = DatabaseService.Instance; // For AudioFingerprinting IPermutations permutations = new LocalPermutations("Soundfingerprinting\\perms.csv", ","); //IPermutations permutations = new LocalPermutations("Soundfingerprinting\\perms-new.csv", ","); Repository repository = new Repository(permutations, databaseService, fingerprintService); if (scanPath != "") { if (IOUtils.IsDirectory(scanPath)) { if (resetdb) { // For MandelEllis and Scms mandelEllisScmsDatabase.RemoveTable(); mandelEllisScmsDatabase.AddTable(); // For AudioFingerprinting databaseService.RemoveFingerprintTable(); databaseService.AddFingerprintTable(); databaseService.RemoveHashBinTable(); databaseService.AddHashBinTable(); databaseService.RemoveTrackTable(); databaseService.AddTrackTable(); } Console.WriteLine("FindSimilar. Version {0}.", VERSION); ScanDirectory(scanPath, mandelEllisScmsDatabase, repository, skipDurationAboveSeconds, silent); } else { Console.Out.WriteLine("No directory found {0}!", scanPath); } } if (queryPath != "") { FileInfo fi = new FileInfo(queryPath); if (fi.Exists) { FindSimilar(queryPath, mandelEllisScmsDatabase, analysisMethod, numToTake, percentage, distanceType); } else { Console.Out.WriteLine("No file found {0}!", queryPath); } } if (queryId != -1) { FindSimilar(new int[] { queryId }, mandelEllisScmsDatabase, analysisMethod, numToTake, percentage, distanceType); } System.Console.ReadLine(); }
public IActionResult PatientSignUp(PatientSignUpViewModel patientSignUpViewModel) { // Description: Registers a patient up for a MedNet account ViewBag.DoctorName = HttpContext.Session.GetString(Globals.currentUserName); string signPrivateKey = null, agreePrivateKey = null, signPublicKey = null, agreePublicKey = null; Assets <PatientCredAssetData> userAsset = _bigChainDbService.GetPatientAssetFromID(patientSignUpViewModel.PHN); // Check if PHN is already in use if (userAsset != null) { ModelState.AddModelError("", "A Patient profile with that PHN already exists"); return(View(patientSignUpViewModel)); } // Register fingerprint information int numScans = 5; List <Image> fpList = FingerprintService.authenticateFP("24.84.225.22", numScans); List <byte[]> fpdb = new List <byte[]>(); if (fpList.Count > numScans) { ModelState.AddModelError("", "Something went wrong with the fingerprint scan, try again."); return(View(patientSignUpViewModel)); } // Parse the input data for user registration var passphrase = patientSignUpViewModel.KeyWord; var password = patientSignUpViewModel.Password; // Encrypt fingerprint data List <string> encrList = new List <string>(); foreach (var fp in fpList) { byte[] fpByte = FingerprintService.imgToByte(fp); string encrStr = EncryptionService.encryptFingerprintData(patientSignUpViewModel.PHN, passphrase, fpByte); encrList.Add(encrStr); } // Create a user for the Blockchain EncryptionService.getNewBlockchainUser(out signPrivateKey, out signPublicKey, out agreePrivateKey, out agreePublicKey); // Create the user Asset var userAssetData = new PatientCredAssetData { ID = patientSignUpViewModel.PHN, DateOfBirth = patientSignUpViewModel.DateOfBirth, PrivateKeys = EncryptionService.encryptPrivateKeys(patientSignUpViewModel.PHN, passphrase, signPrivateKey, agreePrivateKey), DateOfRecord = DateTime.Now, SignPublicKey = signPublicKey, AgreePublicKey = agreePublicKey, FingerprintData = encrList, }; // Encrypt the user's password in the metadata var userMetadata = new PatientCredMetadata { FirstName = patientSignUpViewModel.FirstName, LastName = patientSignUpViewModel.LastName, Email = patientSignUpViewModel.Email, hashedPassword = EncryptionService.hashPassword(password) }; // Save the user Asset and Metadata var asset = new AssetSaved <PatientCredAssetData> { Type = AssetType.Patient, Data = userAssetData, RandomId = _random.Next(0, 100000) }; var metadata = new MetaDataSaved <PatientCredMetadata> { data = userMetadata }; // Send the user's information to the Blockchain database _bigChainDbService.SendCreateTransactionToDataBase(asset, metadata, signPrivateKey); return(RedirectToAction("PatientLookUp")); }
public CompareAudioForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); // // TODO: Add constructor code after the InitializeComponent() call. // // Instansiate Soundfingerprinting Repository FingerprintService fingerprintService = Analyzer.GetSoundfingerprintingService(); this.databaseService = DatabaseService.Instance; IPermutations permutations = new LocalPermutations("Soundfingerprinting\\perms.csv", ","); //IPermutations permutations = new LocalPermutations("Soundfingerprinting\\perms-new.csv", ","); IFingerprintingConfiguration fingerprintingConfigCreation = new FullFrequencyFingerprintingConfiguration(); repository = new Repository(permutations, databaseService, fingerprintService); ImageService imageService = new ImageService(fingerprintService.SpectrumService, fingerprintService.WaveletService); FileInfo filePathAudio1 = new FileInfo(@"C:\Users\perivar.nerseth\Music\Test Samples Database\VDUB1 Snare 004.wav"); FileInfo filePathAudio2 = new FileInfo(@"C:\Users\perivar.nerseth\Music\Test Samples Search\VDUB1 Snare 004 - Start.wav"); int fingerprintsPerRow = 2; double[][] logSpectrogram1 = null; double[][] logSpectrogram2 = null; List <bool[]> fingerprints1 = null; List <bool[]> fingerprints2 = null; WorkUnitParameterObject file1Param = Analyzer.GetWorkUnitParameterObjectFromAudioFile(filePathAudio1); if (file1Param != null) { file1Param.FingerprintingConfiguration = fingerprintingConfigCreation; // Get fingerprints fingerprints1 = fingerprintService.CreateFingerprintsFromAudioSamples(file1Param.AudioSamples, file1Param, out logSpectrogram1); pictureBox1.Image = imageService.GetSpectrogramImage(logSpectrogram1, logSpectrogram1.Length, logSpectrogram1[0].Length); pictureBoxWithInterpolationMode1.Image = imageService.GetImageForFingerprints(fingerprints1, file1Param.FingerprintingConfiguration.FingerprintLength, file1Param.FingerprintingConfiguration.LogBins, fingerprintsPerRow); } WorkUnitParameterObject file2Param = Analyzer.GetWorkUnitParameterObjectFromAudioFile(filePathAudio2); if (file2Param != null) { file2Param.FingerprintingConfiguration = fingerprintingConfigCreation; // Get fingerprints fingerprints2 = fingerprintService.CreateFingerprintsFromAudioSamples(file2Param.AudioSamples, file2Param, out logSpectrogram2); pictureBox2.Image = imageService.GetSpectrogramImage(logSpectrogram2, logSpectrogram2.Length, logSpectrogram2[0].Length); pictureBoxWithInterpolationMode2.Image = imageService.GetImageForFingerprints(fingerprints2, file2Param.FingerprintingConfiguration.FingerprintLength, file2Param.FingerprintingConfiguration.LogBins, fingerprintsPerRow); } MinHash minHash = repository.MinHash; // only use the first signatures bool[] signature1 = fingerprints1[0]; bool[] signature2 = fingerprints2[0]; if (signature1 != null && signature2 != null) { int hammingDistance = MinHash.CalculateHammingDistance(signature1, signature2); double jaqSimilarity = MinHash.CalculateJaqSimilarity(signature1, signature2); lblSimilarity.Text = String.Format("Hamming: {0} JAQ: {1}", hammingDistance, jaqSimilarity); } }
public IActionResult FillPrescription(FillPrescriptionViewModel fillPrescriptionViewModel) { // Get's the Doctor's information for current session ViewBag.DoctorName = HttpContext.Session.GetString(Globals.currentUserName); var oldViewModel = JsonConvert.DeserializeObject <FillPrescriptionViewModel>(TempData["viewModel"] as string); fillPrescriptionViewModel.PrescriptionData = oldViewModel.PrescriptionData; fillPrescriptionViewModel.PatientAsset = oldViewModel.PatientAsset; fillPrescriptionViewModel.PatientMetadata = oldViewModel.PatientMetadata; TempData["viewModel"] = JsonConvert.SerializeObject(fillPrescriptionViewModel); if (!ModelState.IsValid) { return(View(fillPrescriptionViewModel)); } string PHN = HttpContext.Session.GetString(Globals.currentPPHN); string patientSignPublicKey = HttpContext.Session.GetString(Globals.currentPSPubK); string keyword = fillPrescriptionViewModel.PatientKeyword; // Searches for a patient with the specified PHN Assets <UserCredAssetData> userAsset = _bigChainDbService.GetUserAssetFromTypeID(AssetType.Patient, PHN); if (userAsset == null) { ModelState.AddModelError("", "Could not find a patient profile with PHN: " + PHN); return(View(fillPrescriptionViewModel)); } // Send request to the Client Computer to authenticate with fingerprint int numScans = 1; List <Image> fpList = FingerprintService.authenticateFP("24.84.225.22", numScans); // DEBUG: Jacob's Computer // Check if fingerprint data is valid if (fpList.Count < numScans) { ModelState.AddModelError("", "Something went wrong with the fingerprint scan, try again."); return(View(fillPrescriptionViewModel)); } Image fpImg = fpList[0]; // Decrypt the patient's fingerprint data stored in the Blockchain byte[] dbFpData = null; string patientSignPrivateKey, patientAgreePrivateKey; List <string> dbList = userAsset.data.Data.FingerprintData; List <Image> dbfpList = new List <Image>(); try { foreach (string db in dbList) { EncryptionService.decryptFingerprintData(PHN, keyword, db, out dbFpData); dbfpList.Add(FingerprintService.byteToImg(dbFpData)); } EncryptionService.getPrivateKeyFromIDKeyword(PHN, keyword, userAsset.data.Data.PrivateKeys, out patientSignPrivateKey, out patientAgreePrivateKey); } catch { ModelState.AddModelError("", "Keyword may be incorrect"); return(View(fillPrescriptionViewModel)); } // Compare the scanned fingerprint with the one saved in the database if (!FingerprintService.compareFP(fpImg, dbfpList)) { ModelState.AddModelError("", "The fingerprint did not match, try again."); return(View(fillPrescriptionViewModel)); } var prescriptionData = _bigChainDbService.GetMetaDataAndAssetFromTransactionId <string, PrescriptionMetadata> (fillPrescriptionViewModel.PrescriptionData.transID); var oldMetadata = prescriptionData.metadata; if (fillPrescriptionViewModel.PrescriptionData.assetData.EndDate.CompareTo(DateTime.Now) < 0) { ModelState.AddModelError("", "The Prescription seems to have expired. Cannot fill this prescription."); return(View(fillPrescriptionViewModel)); } if (fillPrescriptionViewModel.PrescriptionData.Metadata.RefillRemaining < fillPrescriptionViewModel.QtyFilled) { ModelState.AddModelError("", "Connot issue more than remaining refills."); } MetaDataSaved <PrescriptionMetadata> newMetadata = oldMetadata; newMetadata.data.LastIssueQty = fillPrescriptionViewModel.QtyFilled; newMetadata.data.LastIssueDate = DateTime.Now; newMetadata.data.RefillRemaining = fillPrescriptionViewModel.PrescriptionData.Metadata.RefillRemaining - fillPrescriptionViewModel.QtyFilled; _bigChainDbService.SendTransferTransactionToDataBase <PrescriptionMetadata>(fillPrescriptionViewModel.PrescriptionData.assetID, newMetadata, patientSignPrivateKey, patientSignPublicKey, fillPrescriptionViewModel.PrescriptionData.transID); return(RedirectToAction("PatientRecords")); }