43 lines
		
	
	
		
			1.0 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			43 lines
		
	
	
		
			1.0 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
| namespace AAIntegration.SimmonsBank.API.Services;
 | |
| 
 | |
| using AutoMapper;
 | |
| using BCrypt.Net;
 | |
| using AAIntegration.SimmonsBank.API.Config;
 | |
| using System;
 | |
| using System.Security.Cryptography;
 | |
| 
 | |
| public interface IApiKeyService
 | |
| {
 | |
|     string GenerateApiKey();
 | |
| }
 | |
| 
 | |
| public class ApiKeyService : IApiKeyService
 | |
| {
 | |
|     private DataContext _context;
 | |
|     private readonly IMapper _mapper;
 | |
| 
 | |
|     public ApiKeyService(
 | |
|         DataContext context,
 | |
|         IMapper mapper)
 | |
|     {
 | |
|         _context = context;
 | |
|         _mapper = mapper;
 | |
|     }
 | |
| 
 | |
|     private const string _prefix = "CT-";
 | |
|     private const int _numberOfSecureBytesToGenerate = 32;
 | |
|     private const int _lengthOfKey = 32;
 | |
|     
 | |
|     public string GenerateApiKey()
 | |
|     {
 | |
|         var bytes = RandomNumberGenerator.GetBytes(_numberOfSecureBytesToGenerate);
 | |
| 
 | |
|         string base64String = Convert.ToBase64String(bytes)
 | |
|             .Replace("+", "-")
 | |
|             .Replace("/", "_");
 | |
|         
 | |
|         var keyLength = _lengthOfKey - _prefix.Length; 
 | |
| 
 | |
|         return _prefix + base64String[..keyLength];
 | |
|     }
 | |
| } |