{"id":37736,"date":"2024-12-09T10:23:41","date_gmt":"2024-12-09T09:23:41","guid":{"rendered":"https:\/\/help.qualiware.it\/qw-help\/?p=37736"},"modified":"2024-12-09T11:09:17","modified_gmt":"2024-12-09T10:09:17","slug":"invio-dati-ad-un-web-service-rest-con-utilizzo-di-un-certificato-p12-con-codifica-ecdh-o-ecdsa-e-token-jwt","status":"publish","type":"post","link":"https:\/\/help.qualiware.it\/qw-help\/invio-dati-ad-un-web-service-rest-con-utilizzo-di-un-certificato-p12-con-codifica-ecdh-o-ecdsa-e-token-jwt\/","title":{"rendered":"Invio dati ad un Web Service REST con utilizzo di un certificato P12 con codifica ECDH o ECDSA e token JWT"},"content":{"rendered":"<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">' Il seguente codice invia dati ad un Web Service REST con utilizzo di un certificato P12 con codifica ECDH o ECDSA.\r\n' Da notare che questo tipo di codifica \u00e8 la pi\u00f9 recente e pi\u00f9 sicura e che il codice pu\u00f2 essere adattato anche per codifica RSA.\r\n' Questo codice funziona con QualiWare 2023.02.14 o successivo.\r\n\r\n' L'esempio da cui \u00e8 tratto questo codice si trova qui: https:\/\/demoapi.rentri.gov.it\/docs?page=esempi#certificato-di-dominio\r\n\r\nDim certificatePath As String = \"&lt;percorso del file del certificato in formato P12 o PFX&gt;\"\r\nDim tempPath As String = form.GetSession().GetLocalTempFileName(\".p12\")\r\nSystem.IO.File.Copy(certificatePath, tempPath)\r\n\r\nDim password As String = \"&lt;password del certificato&gt;\"\r\nTry\r\n       \r\n    dim certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(tempPath, password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable)\r\n    Dim p12 as String=Convert.ToBase64String(certificate.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, password), Base64FormattingOptions.InsertLineBreaks)   \r\n\r\n    ' Generazione del JWT\r\n    Dim jsonData1 As String = \"[{\"\"riferimenti\"\":{\"\"numero_registrazione\"\":{\"\"anno\"\":2024,\"\"progressivo\"\":1},\"\"data_ora_registrazione\"\":\"\"2024-05-09T09:16:54.729Z\"\",\"\"causale_operazione\"\":\"\"aT\"\"},\"\"rifiuto\"\":{\"\"codice_eer\"\":\"\"150101\"\",\"\"stato_fisico\"\":\"\"SP\"\",\"\"quantita\"\":{\"\"valore\"\":5000.1234,\"\"unita_misura\"\":\"\"kg\"\"}}}]\"  ' Dati da spedire\r\n    \r\n    Dim content as New System.Net.Http.StringContent(jsonData1, System.Text.Encoding.UTF8, \"application\/json\")\r\n\r\n    Dim cert1 as New System.Security.Cryptography.X509Certificates.X509Certificate2(Convert.FromBase64String(p12), password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet Or System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.EphemeralKeySet)\r\n    Dim algo = Microsoft.IdentityModel.Tokens.SecurityAlgorithms.EcdsaSha256\r\n\r\n    Dim issuer = \"01687751204\"\r\n    Dim regId = \"RCEZ3LS9SJ0\"\r\n    Dim aud = \"rentrigov.demo.api\"\r\n    Dim baseApi = \"https:\/\/demoapi.rentri.gov.it\"\r\n    Dim api = $\"{baseApi}\/dati-registri\/v1.0\/operatore\/{regId}\/movimenti\"\r\n    Dim jti = Guid.NewGuid().ToString()\r\n\r\n    Dim tokenHandler = New Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler()\r\n    Dim tokenDescriptor = New Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor With {\r\n    .AdditionalHeaderClaims = New System.Collections.Generic.Dictionary(Of String, Object) From {\r\n        {\"x5c\", New String() {Convert.ToBase64String(cert1.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert))}}\r\n        },\r\n        .Audience = aud,\r\n        .Issuer = issuer,\r\n        .Claims = New System.Collections.Generic.Dictionary(Of String, Object) From {\r\n            {\"jti\", jti}\r\n        },\r\n        .SigningCredentials = New Microsoft.IdentityModel.Tokens.SigningCredentials(New Microsoft.IdentityModel.Tokens.ECDsaSecurityKey(System.Security.Cryptography.X509Certificates.ECDsaCertificateExtensions.GetECDsaPrivateKey(cert1)), \"ES256\")\r\n    }\r\n    Dim idAuth = tokenHandler.CreateToken(tokenDescriptor)\r\n\r\n    dim sha256 As System.Security.Cryptography.SHA256 = System.Security.Cryptography.SHA256.Create()\r\n    dim digest = $\"SHA-256={Convert.ToBase64String(sha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(jsonData1)))}\"\r\n\r\n    ' Aggiunge le intestazioni firmate ai claim\r\n    tokenDescriptor.Claims.Add(\"signed_headers\", New System.Collections.Generic.Dictionary(Of String, String)() {\r\n        New System.Collections.Generic.Dictionary(Of String, String)() From {{\"digest\", digest}}, \r\n        New System.Collections.Generic.Dictionary(Of String, String)() From {{\"content-type\", content.Headers.ContentType.ToString()}}\r\n    })\r\n\r\n    dim integrity = tokenHandler.CreateToken(tokenDescriptor)\r\n\r\n    ' Configura la richiesta HTTP\r\n    Dim request As System.Net.HttpWebRequest = CType(System.Net.WebRequest.Create(api), System.Net.HttpWebRequest)\r\n    request.Method = \"POST\"\r\n    request.ContentType=content.Headers.ContentType.ToString()\r\n    request.Headers.Add(\"Authorization\", \"Bearer \" &amp; idAuth)\r\n    request.Headers.Add(\"Agid-JWT-Signature\", integrity)\r\n    request.Headers.Add(\"Digest\", digest)\r\n\r\n    Using requestStream As System.IO.Stream = request.GetRequestStream()\r\n        Using writer As New System.IO.StreamWriter(requestStream)\r\n            writer.Write(jsonData1)\r\n        End Using\r\n    End Using\r\n\r\n    ' Ottieni la risposta\r\n    try\r\n        Using response As System.Net.HttpWebResponse = CType(request.GetResponse(), System.Net.HttpWebResponse)\r\n            If response.StatusCode = 200 Then\r\n                Using streamReader As New System.IO.StreamReader(response.GetResponseStream())\r\n                    Dim responseText As String = streamReader.ReadToEnd()\r\n                    form.Alert(\"Risposta ricevuta: \" &amp; responseText)\r\n                End Using\r\n            Else\r\n                form.Alert(\"Status: \" &amp; LTrim(Str(response.StatusCode)) &amp; \" \" &amp; response.StatusDescription)\r\n            End If\r\n        End Using\r\n    Catch e as Exception\r\n        form.alert(e.message)\r\n    End Try\r\nCatch ex As Exception\r\n    form.Alert(\"Errore: \" &amp; ex.Message &amp; vbCrLf &amp; ex.StackTrace)\r\nEnd Try\r\n\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>&#8216; Il seguente codice invia dati ad un Web Service REST con utilizzo di un certificato P12 con codifica ECDH o ECDSA. &#8216; Da notare che questo tipo di codifica \u00e8 la pi\u00f9 recente e pi\u00f9 sicura e che il codice pu\u00f2 essere adattato anche per codifica RSA. &#8216; Questo codice funziona con QualiWare 2023.02.14&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"ngg_post_thumbnail":0,"footnotes":""},"categories":[65],"tags":[71,82],"acf":[],"_links":{"self":[{"href":"https:\/\/help.qualiware.it\/qw-help\/wp-json\/wp\/v2\/posts\/37736"}],"collection":[{"href":"https:\/\/help.qualiware.it\/qw-help\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/help.qualiware.it\/qw-help\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/help.qualiware.it\/qw-help\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/help.qualiware.it\/qw-help\/wp-json\/wp\/v2\/comments?post=37736"}],"version-history":[{"count":3,"href":"https:\/\/help.qualiware.it\/qw-help\/wp-json\/wp\/v2\/posts\/37736\/revisions"}],"predecessor-version":[{"id":37739,"href":"https:\/\/help.qualiware.it\/qw-help\/wp-json\/wp\/v2\/posts\/37736\/revisions\/37739"}],"wp:attachment":[{"href":"https:\/\/help.qualiware.it\/qw-help\/wp-json\/wp\/v2\/media?parent=37736"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/help.qualiware.it\/qw-help\/wp-json\/wp\/v2\/categories?post=37736"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/help.qualiware.it\/qw-help\/wp-json\/wp\/v2\/tags?post=37736"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}