API .Net HSM Dinamo
API Proprietária .Net do HSM Dinamo
oath.cs

Exemplo de uso de geração de tokens OATH, validação e atualização do blob para evitar ataque de noreply.

Veja Nota sobre os exemplos.
using System;
using Dinamo.Hsm;
using System.IO;
using QRCoder;
using System.Text;
namespace ConsoleATesteCheckOTPpp1
{
class Program
{
private static string HSM_HOST = "200.201.208.61";
private static string HSM_USER = "tstotp";
private static string HSM_PASS = "12345678";
private static string HSM_KEY = "key_c";
private static string BLOB_PATH = @".\blob_otp.bin"; // Atualizar na base de dados - ligado ao usuario
private static string QRCODE_PATH = @".\seed_otp.jpg";
static void Main(string[] args)
{
DinamoClient client = new DinamoClient();
client.Connect(HSM_HOST, HSM_USER, HSM_PASS);
// Gera a chave se nao tiver
if (!client.IsKeyExist(HSM_KEY))
{
client.GenerateKey(HSM_KEY, DinamoClient.KEY_ALG.ALG_AES_256, false);
}
// Gera OTP
byte[] blob = null;
if (!File.Exists(BLOB_PATH))
{
blob = client.OATHIssueGenerateTOTP(HSM_KEY, 30);
File.WriteAllBytes(BLOB_PATH, blob);
}
else
{
blob = File.ReadAllBytes(BLOB_PATH);
}
if (!File.Exists(QRCODE_PATH))
{
QRCodeGenerator qrGenerator = new QRCodeGenerator();
byte[] seed = client.OATHGetKey(HSM_KEY, blob);
string seed_base32 = client.EncodeBase32(seed);
string payload = string.Format("otpauth://totp/Dinamo:teste?secret={0}&algorithm=SHA1&digits=6&period=30", seed_base32);
QRCodeData qrCodeData = qrGenerator.CreateQrCode(payload, QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new QRCode(qrCodeData);
System.Drawing.Bitmap fig = qrCode.GetGraphic(20);
fig.Save(QRCODE_PATH, System.Drawing.Imaging.ImageFormat.Jpeg);
}
string otp = "";
DinamoClient client2 = new DinamoClient();
client2.Connect(HSM_HOST, HSM_USER, HSM_PASS);
do
{
// Pode-se usar a função se quiser que o HSM gere um OTP, ou seja, envio por SMS
//Console.Out.WriteLine("Valor do próximo OTP:{0}", client.OATHGetNext(HSM_KEY, DinamoApi.ISSUE_OATH_MIN_OTP_LEN, blob));
//
//No cenário que dispomos de um Google Autenticator para gerar o valor:
Console.Out.Write("Digite o valor do OTP:");
otp = Console.In.ReadLine();
if (client.OATHCheck(HSM_KEY, otp, blob, 10)) // 10 janelas de 30 segundos
{
Console.Out.WriteLine("OTP Valido!!!");
File.WriteAllBytes(BLOB_PATH, blob);
}
else
{
Console.Out.WriteLine("OTP Invalido!!!");
}
} while (otp != "");
client2.Disconnect();
Console.Out.WriteLine("Arquivo gerado");
client.Disconnect();
}
}
}
Namespace que denota um conjunto de funções para acesso ao HSM Dinamo e suas respectivas exceptions.
Definition: DinamoClient.cs:12
Definition: DinamoClient.cs:12