Mifare DESFire EV1 4K AES authentication issue - authentication

Please, can someone tell me what I'm doing wrong. I have to AES authenticate my card. The card is Mifare DESFire EV1 4K and the reader is Omnikey 5121. I followed some examples here on Stack but I always fail in the last step where card's rotated RndA is not equal to my rotated RndA. Is something wrong with the AES configuration?
public static byte[] Authenticate_AES(this SCardReader reader, byte[] key)
{
using (var aes = Aes.Create())
{
aes.Key = key;
aes.Padding = PaddingMode.None;
aes.Mode = CipherMode.CBC;
aes.BlockSize = 128;
aes.IV = SCardUtils.StringToByteArray("00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00");
var decryptor = aes.CreateDecryptor();
var encryptor = aes.CreateEncryptor();
var rnd = new Random();
//Get encrypted RandB from the card
var rAPDU = reader.Transmit(0x90, 0xAA, 0, 0, SCardUtils.StringToByteArray("00"));
if (!rAPDU.HasData)
throw new Exception("RandB_enc is null");
//Encrypted RndB
var RndB_enc = new byte[16];
rAPDU.Data.CopyTo(RndB_enc, 0);
SCardUtils.ShowBytes(RndB_enc, "RndB_enc");
//Decrypt encrypted RndB
var RndB = decryptor.TransformFinalBlock(RndB_enc, 0, RndB_enc.Length);
SCardUtils.ShowBytes(RndB, "RndB");
//Rotate RndB 1 byte to the left
var RndB_rot = SCardUtils.RotateLeft(RndB);
SCardUtils.ShowBytes(RndB_rot, "RndB_rot");
//Generate random RndA
var RndA = new byte[16];
rnd.NextBytes(RndA);
SCardUtils.ShowBytes(RndA, "RndA");
//Concatenate RndA and RndB_rot
var RndAB_rot = RndA.Concat(RndB_rot).ToArray();
SCardUtils.ShowBytes(RndAB_rot, "RndAB_rot");
//Encypt RndAB_rot
var dataToSend = encryptor.TransformFinalBlock(RndAB_rot, 0, RndAB_rot.Length);
SCardUtils.ShowBytes(dataToSend, "Encrypted data");
rAPDU = reader.Transmit(0x90, 0xAF, 0, 0, dataToSend);
if (!rAPDU.HasData)
throw new Exception("rAPDU data is null");
//Encrypted RndA_rot
var RndA_rot_enc = new byte[16];
rAPDU.Data.CopyTo(RndA_rot_enc, 0);
SCardUtils.ShowBytes(RndA_rot_enc, "RndA_rot_enc");
//Decrypt encrypted RndA_rot
var RndA_rot_dec = decryptor.TransformFinalBlock(RndA_rot_enc, 0, RndA_rot_enc.Length);
SCardUtils.ShowBytes(RndA_rot_dec, "RndA_rot_dec");
var RndA_rot = SCardUtils.RotateLeft(RndA);
SCardUtils.ShowBytes(RndA_rot, "RndA_rot");
//Compare RndA_rot with RndA rotated to the left
if (!SCardUtils.IsEqualTo(RndA_rot_dec, RndA_rot))
throw new Exception($"Error authenticating card. The values are not equal.");
var sessionKey = new byte[16];
Array.Copy(RndA, 0, sessionKey, 0, 4);
Array.Copy(RndB, 0, sessionKey, 4, 4);
Array.Copy(RndA, 12, sessionKey, 8, 4);
Array.Copy(RndB, 12, sessionKey, 12, 4);
return sessionKey;
}
}
Here is the output:
Reader name: OMNIKEY CardMan 5x21-CL 0
RndB_enc: 08 DD A2 12 57 43 6C F7 75 98 78 9E 6C 0A A7 06
RndB: 16 C8 35 7A 4A 36 29 D2 F0 86 26 AD FA CA 81 9F
RndB_rot: C8 35 7A 4A 36 29 D2 F0 86 26 AD FA CA 81 9F 16
RndA: 77 93 A5 8D 0E 0D 88 88 22 C3 40 9C 26 67 95 35
RndAB_rot: 77 93 A5 8D 0E 0D 88 88 22 C3 40 9C 26 67 95 35 C8 35 7A 4A 36 29 D2 F0 86 26 AD FA CA 81 9F 16
Data: 4D BD 7A E8 B8 6C 00 5F E4 B5 B5 42 7B AE 51 39 25 77 CB 60 83 6A E8 15 B9 9D FD A9 FD A7 75 9F
RndA_rot_enc: D6 CB CF 08 5F 8A E8 6C 30 95 34 6F DD CF 4F FA
RndA_rot_dec: 6B 70 54 39 CD 8E 97 42 E2 A5 FF E3 90 95 46 E0
RndA_rot: 93 A5 8D 0E 0D 88 88 22 C3 40 9C 26 67 95 35 77
So you can see RndA_rot_dec and RndA_rot are not equal and I can't figure it out why.
Thank you all in advance.

I finally got the solution. I also modified the code a bit so it can be more understandable for everyone who will have a problem as I did. For several weeks.
public static byte[] Authenticate_AES(this SCardReader reader, byte[] key, byte[] IV)
{
//Get encrypted RndB from the tag
var rAPDU = reader.Transmit(0x90, 0xAA, 0, 0, SCardUtils.StringToByteArray("00"));
if (!rAPDU.HasData)
throw new Exception("RandB_enc is null");
var aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.KeySize = 128;
aes.BlockSize = 128;
aes.Padding = PaddingMode.None;
aes.Key = key;
aes.IV = IV; //16 bytes of zeros
//Encrypted RndB from the tag
var RndB_enc = rAPDU.Data.ToArray();
SCardUtils.ShowBytes(RndB_enc, "RndB_enc");
var decryptor = aes.CreateDecryptor();
//Decrypt encrypted RndB
var RndB = decryptor.TransformFinalBlock(RndB_enc, 0, RndB_enc.Length);
SCardUtils.ShowBytes(RndB, "RndB");
//Rotate RndB 1 byte to the left
var RndB_rot = SCardUtils.RotateLeft(RndB);
SCardUtils.ShowBytes(RndB_rot, "RndB_rot");
var rnd = new Random();
//Generate random RndA
var RndA = new byte[16];
rnd.NextBytes(RndA);
SCardUtils.ShowBytes(RndA, "RndA");
//Concatenate RndA and RndB_rot
var RndAB_rot = RndA.Concat(RndB_rot).ToArray();
SCardUtils.ShowBytes(RndAB_rot, "RndAB_rot");
//IV is now encrypted RndB received from the tag
aes.IV = RndB_enc;
var encryptor = aes.CreateEncryptor();
//Encypt RndAB_rot
var RndAB_rot_enc = encryptor.TransformFinalBlock(RndAB_rot, 0, RndAB_rot.Length);
SCardUtils.ShowBytes(RndAB_rot_enc, "RndAB_rot_enc");
rAPDU = reader.Transmit(0x90, 0xAF, 0, 0, RndAB_rot_enc);
if (!rAPDU.HasData)
throw new Exception("rAPDU data is null");
//Encrypted RndA_rot from the tag
var RndA_rot_enc = rAPDU.Data.ToArray();
SCardUtils.ShowBytes(RndA_rot_enc, "RndA_rot_enc");
//IV is now the last 16 bytes of RndAB_rot_enc
aes.IV = RndAB_rot_enc.Skip(16).Take(16).ToArray();
decryptor = aes.CreateDecryptor();
//Decrypt encrypted RndA_rot
var RndA_rot = decryptor.TransformFinalBlock(rAPDU.Data, 0, rAPDU.Data.Length);
SCardUtils.ShowBytes(RndA_rot, "RndA_rot");
//Compare RndA_rot_dec with RndA_rot
if (!SCardUtils.IsEqualTo(RndA_rot, SCardUtils.RotateLeft(RndA)))
throw new Exception($"Error authenticating card. The values are not equal.");
var sessionKey = new byte[16];
Array.Copy(RndA, 0, sessionKey, 0, 4);
Array.Copy(RndB, 0, sessionKey, 4, 4);
Array.Copy(RndA, 12, sessionKey, 8, 4);
Array.Copy(RndB, 12, sessionKey, 12, 4);
aes.Clear();
return sessionKey;
}
The problem was with Init Vector. It is changing through the three-pass authentication.
Here is the final output:
Reader name: OMNIKEY CardMan 5x21-CL 0
RndB_enc: 6F 40 6D 9D 51 7A 2C 9E 88 C9 2C 84 80 94 E3 F7
RndB: FB FB A7 5F 54 97 D7 CA 4B 15 07 F1 A0 D1 A2 68
RndB_rot: FB A7 5F 54 97 D7 CA 4B 15 07 F1 A0 D1 A2 68 FB
RndA: 87 7B BA 48 4D 01 14 CE 4D 8E 33 A5 1B 0F 00 E9
RndAB_rot: 87 7B BA 48 4D 01 14 CE 4D 8E 33 A5 1B 0F 00 E9 FB A7 5F 54 97 D7 CA 4B 15 07 F1 A0 D1 A2 68 FB
RndAB_rot_enc: 0B 8B 4E D9 BF 40 51 F0 83 FC 44 E8 B7 A7 21 26 DE A9 B9 CE E5 05 F7 A5 46 FE 91 0F 59 2B 90 E7
RndA_rot_enc: 9F 3D E8 90 37 2E 7B F6 1E BA AC 29 6E 94 1C 9E
RndA_rot: 7B BA 48 4D 01 14 CE 4D 8E 33 A5 1B 0F 00 E9 87
As you can see RndA (line 5) rotated 1 byte to the left is equal to RndA_rot (last line). With this authentication is completed.

Related

GCP client library not working - SSL peer shut down incorrectly

I have sample code to fetch regions from Google Cloud API. This sample code works fine from my laptop (windows with OpenJDK 1.8 version). But the same code fails from kubernetes environment which has suse linux with OpenJDK 1.8 version.
From Suse linux side I get :
Exception in thread "main" java.io.IOException: Error getting access token for service account: Remote host closed connection during handshake
at com.google.auth.oauth2.ServiceAccountCredentials.refreshAccessToken(ServiceAccountCredentials.java:444)
at com.google.auth.oauth2.OAuth2Credentials.refresh(OAuth2Credentials.java:157)
at com.google.auth.oauth2.OAuth2Credentials.getRequestMetadata(OAuth2Credentials.java:145)
at com.google.auth.oauth2.ServiceAccountCredentials.getRequestMetadata(ServiceAccountCredentials.java:603)
at com.google.auth.http.HttpCredentialsAdapter.initialize(HttpCredentialsAdapter.java:91)
at com.google.api.client.http.HttpRequestFactory.buildRequest(HttpRequestFactory.java:91)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.buildHttpRequest(AbstractGoogleClientRequest.java:404)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:514)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:455)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:565)
at sample.program.gcp.vpvn.regionList(vpvn.java:85)
at sample.program.gcp.vpvn.main(vpvn.java:307)
Caused by: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:994)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1340)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1315)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:264)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:113)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:84)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1012)
at com.google.auth.oauth2.ServiceAccountCredentials.refreshAccessToken(ServiceAccountCredentials.java:441)
... 11 more
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at sun.security.ssl.InputRecord.read(InputRecord.java:505)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:975)
... 23 more
When I enable SSL debug, I am not getting much details to troubleshoot this issue:
*** ClientHello, TLSv1.2
RandomCookie: GMT: 1616080171 bytes = { 119, 66, 219, 23, 171, 247, 221, 79, 45, 202, 181, 18, 229, 4, 65, 98, 207, 90, 0, 108, 43, 54, 80, 65, 39, 31, 49, 114 }
Session ID: {}
Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, TLS_RSA_WITH_AES_256_CBC_SHA256, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_DSS_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
Compression Methods: { 0 }
***
[write] MD5 and SHA1 hashes: len = 215
0000: 01 00 00 D3 03 03 60 53 6D 2B 77 42 DB 17 AB F7 ......`Sm+wB....
0010: DD 4F 2D CA B5 12 E5 04 41 62 CF 5A 00 6C 2B 36 .O-.....Ab.Z.l+6
0020: 50 41 27 1F 31 72 00 00 56 C0 24 C0 28 00 3D C0 PA'.1r..V.$.(.=.
0030: 26 C0 2A 00 6B 00 6A C0 0A C0 14 00 35 C0 05 C0 &.*.k.j.....5...
0040: 0F 00 39 00 38 C0 23 C0 27 00 3C C0 25 C0 29 00 ..9.8.#.'.<.%.).
0050: 67 00 40 C0 09 C0 13 00 2F C0 04 C0 0E 00 33 00 g.#...../.....3.
0060: 32 C0 2C C0 2B C0 30 00 9D C0 2E C0 32 00 9F 00 2.,.+.0.....2...
0070: A3 C0 2F 00 9C C0 2D C0 31 00 9E 00 A2 00 FF 01 ../...-.1.......
0080: 00 00 54 00 0A 00 08 00 06 00 17 00 18 00 19 00 ..T.............
0090: 0B 00 02 01 00 00 0D 00 1C 00 1A 06 03 06 01 05 ................
00A0: 03 05 01 04 03 04 01 04 02 03 03 03 01 03 02 02 ................
00B0: 03 02 01 02 02 00 17 00 00 00 00 00 1A 00 18 00 ................
00C0: 00 15 6F 61 75 74 68 32 2E 67 6F 6F 67 6C 65 61 ..oauth2.googlea
00D0: 70 69 73 2E 63 6F 6D pis.com
main, WRITE: TLSv1.2 Handshake, length = 215
[Raw write]: length = 220
0000: 16 03 03 00 D7 01 00 00 D3 03 03 60 53 6D 2B 77 ...........`Sm+w
0010: 42 DB 17 AB F7 DD 4F 2D CA B5 12 E5 04 41 62 CF B.....O-.....Ab.
0020: 5A 00 6C 2B 36 50 41 27 1F 31 72 00 00 56 C0 24 Z.l+6PA'.1r..V.$
0030: C0 28 00 3D C0 26 C0 2A 00 6B 00 6A C0 0A C0 14 .(.=.&.*.k.j....
0040: 00 35 C0 05 C0 0F 00 39 00 38 C0 23 C0 27 00 3C .5.....9.8.#.'.<
0050: C0 25 C0 29 00 67 00 40 C0 09 C0 13 00 2F C0 04 .%.).g.#...../..
0060: C0 0E 00 33 00 32 C0 2C C0 2B C0 30 00 9D C0 2E ...3.2.,.+.0....
0070: C0 32 00 9F 00 A3 C0 2F 00 9C C0 2D C0 31 00 9E .2...../...-.1..
0080: 00 A2 00 FF 01 00 00 54 00 0A 00 08 00 06 00 17 .......T........
0090: 00 18 00 19 00 0B 00 02 01 00 00 0D 00 1C 00 1A ................
00A0: 06 03 06 01 05 03 05 01 04 03 04 01 04 02 03 03 ................
00B0: 03 01 03 02 02 03 02 01 02 02 00 17 00 00 00 00 ................
00C0: 00 1A 00 18 00 00 15 6F 61 75 74 68 32 2E 67 6F .......oauth2.go
00D0: 6F 67 6C 65 61 70 69 73 2E 63 6F 6D ogleapis.com
main, received EOFException: error
main, handling exception: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
main, SEND TLSv1.2 ALERT: fatal, description = handshake_failure
Any hints on how to troubleshoot this issue?
Here with my sample code:
public static void main(String args[]) throws GeneralSecurityException, IOException {
Compute computeService = createComputeService();
Compute.Regions.List request = computeService.regions().list("imageagg-nonprod");
System.out.println("the list of regions for the selected project is \n");
RegionList response;
do {
response = request.execute();
if (response.getItems() == null) {
continue;
}
request.setPageToken(response.getNextPageToken());
} while (response.getNextPageToken() != null);
ArrayList regionNames = new ArrayList<String>();
HashMap<String, ArrayList<String>> ZoneList = new HashMap<>();
response.getItems().forEach(region -> {
ArrayList<String> zones = new ArrayList<String>();
regionNames.add(region.getName());
region.getZones().forEach(zone -> {
zones.add(Paths.get(URI.create(zone).getPath()).getFileName().toString());
});
ZoneList.put(region.getName(), zones);
});
System.out.println("list of region for selected project is \n");
regionNames.forEach(element -> {
System.out.println(element);
});
System.out.println("the names of regions and Zones for the selected Project is \n");
Set entries = ZoneList.entrySet();
Iterator it = entries.iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
machineList(ZoneList);
}
public static Compute createComputeService() throws IOException, GeneralSecurityException {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
String proxyHostOpt = "web-proxy.in.software.net";
int proxyPort = 8080;
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
HttpTransport abc = new NetHttpTransport.Builder().trustCertificates(GoogleUtils.getCertificateTrustStore())
.setProxy(new Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(proxyHostOpt, proxyPort))).build();
//GoogleCredential credential = GoogleCredential.getApplicationDefault(abc,jsonFactory);
List<String> scopes = new ArrayList<>();
//scopes.add("https://www.googleapis.com/auth/cloud-platform");
String jsonToken = "{\n" + " \"type\": \"service_account\",\n" + " \"project_id\": \"imageagg-nonprod\",\n" + " \"private_key_id\": \"99c871d2855b4d9388cc7a3a670a5764deb8c5e9\",\n" + " \"private_key\": \"-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDh9k2JcCFrDZfm\\ng9DONfKe8xATwljEsW8FXMbPzU5JoXXsy1CYgkeW+eqXguQxFZM3HuI1W+mGBxgE\\n/K2P7XvJxylv7NajpgNmm4KGIh4hOpi+Sn3GVS31ftGM5A/CYKhRpr5uskr5PEin\\nDYxl0hUnfTodJCT+uxPxoCeN8aWuq5s+BapKKB8KVduUqmz3f8GL2Pc5wlm/YyOK\\nJYC781MAzLIFe8cLAVUJrVETqOtFTPCjy0yMGiUKxkyL20C11WFwfdD5ou0SD+6U\\nsT1YD/15KYh9GvV1E2XIPGzVtSHvU9h7FDRqOa+05QP3uDHegrAAib4PHA/A7KPD\\nBwkA6sW/AgMBAAECggEAHCPBtS9vIfdP5uecfcmvHMdVRbiquFgGZOsQYTmGmdnP\\nJz2MnGmBA9a8tc=\\n-----END PRIVATE KEY-----\\n\",\n" + " \"client_email\": \"315654350484-compute#developer.gserviceaccount.com\",\n" + " \"client_id\": \"112960668\",\n" + " \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\n" + " \"token_uri\": \"https://oauth2.googleapis.com/token\",\n" + " \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\",\n" + " \"client_x509_cert_url\": \"https://www.googleapis.com/robot/v1/metadata/x509/315654350484-compute%40developer.gserviceaccount.com\"\n" + "}";
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> map
= objectMapper.readValue(jsonToken, new TypeReference<Map<String,Object>>(){});
scopes.add(ComputeScopes.COMPUTE);
scopes.add(ComputeScopes.CLOUD_PLATFORM);
//scopes.add(ComputeScopes.DEVSTORAGE_FULL_CONTROL);
GoogleCredentials credentials = GoogleCredentials.fromStream(IOUtils.toInputStream(jsonToken, StandardCharsets.UTF_8)).createScoped(scopes);
ServiceAccountCredentials serviceAccountCredentials = ServiceAccountCredentials.fromStream(IOUtils.toInputStream(jsonToken, StandardCharsets.UTF_8));
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
// Making call with credentials1 created with json string and proxy set as per requirements
return new Compute.Builder(abc, jsonFactory, requestInitializer).setApplicationName("hcmx").build();
}
My java version details:
java -version
openjdk version "11" 2018-09-25
OpenJDK Runtime Environment 18.9 (build 11+28)
OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)
Environment where code is running:
[root#hcm-pool-centos76-3 ~]# uname -a
Linux hcm-pool-centos76-3 3.10.0-1062.9.1.el7.x86_64 #1 SMP Fri Dec 6 15:49:49 UTC 2

use STM32 crypto library to generate signature

I used STM32 crypto library(firmware implement) and set private key value generated by openssl , but I can't get the right signature.
No matter what the private key value or all-zero(
"00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"), The R parameter of signature always
"D0 F4 7A FE 2F 31 76 B6 C3 1E BC 09 7E 57 81 0A B9 3A D9 65 01 39 90 D0".
Anyone can help?
int generate_sign(unsigned char* Input){
EC_st.pmA = P_192_a;
...
status = STM32_SHA256_HASH_DigestCompute((uint8_t*)TEST_ca,
sizeof(TEST_ca),
(uint8_t*)MessageDigest,
&MessageDigestLength);
if (status == HASH_SUCCESS)
{
status = STM32_Init_RNG_for_Sign( &RNGstate);
if (status == RNG_SUCCESS)
{
status = ECCinitEC(&EC_st, &Crypto_Buffer );
if (status == ECC_SUCCESS)
{
status = ECCinitPrivKey(&PrivKey, &EC_st, &Crypto_Buffer);
if (status == ECC_SUCCESS)
{
status = ECCsetPrivKeyValue(PrivKey,priv_key,priv_key_size);
if (status == ECC_SUCCESS)
{
status = ECDSAinitSign(&sign, &EC_st, &Crypto_Buffer);
if (status == ECC_SUCCESS)
{
signCtx.pmEC = &EC_st;
signCtx.pmPrivKey = PrivKey;
signCtx.pmRNG = &RNGstate;
status = ECDSAsign(MessageDigest, MessageDigestLength, sign, &signCtx, &Crypto_Buffer);
if (status == ECC_SUCCESS)
{
status = ECDSAgetSignature(sign, E_ECDSA_SIGNATURE_R_VALUE, sign_R, &sign_R_length);
status = ECDSAgetSignature(sign, E_ECDSA_SIGNATURE_S_VALUE, sign_S, &sign_S_length);
}
}
}
}
}
}
}
}
return 0;
}

Crash occurs in mshtml when trying to print the contents of a WebBrowser(ActiveX Control), in MFC Applications using ExecWB

The crash occurs in mshtml when we print the contents of a WebBrowser(ActiveX Control), in MFC Applications.
1) The print dialog is not opening.
For printing from webbrowser, we call the below function
ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_PROMPTUSER, NULL, NULL);
2) The crash starts from preview.js (CPrintDoc_RectComplete method) of ieframe.dll.
3) It is crashing in mshtml, "mshtml!Tree::CIE9DocumentLayout::HandleLayoutBuilderError+0xc6"
4) It is giving "Break instruction exception - code 80000003" .
Could you please let us know if there is any hotfix available for this callstack.
The call stack of the crashing thread is
00 000000ea2e697dc0 00007ffb483c4097 mshtml!Tree::CIE9DocumentLayout::HandleLayoutBuilderError+0xc6
01 000000ea2e697e00 00007ffb47cea9fc mshtml!CMarkupPageLayout::CalcPageLayoutSize+0xa09bcf
02 000000ea2e697f90 00007ffb489a6b86 mshtml!CMarkupPageLayout::CalcTopLayoutSizeWithDefault+0x1c
03 000000ea2e697fc0 00007ffb47b13a7f mshtml!CContainerLayout::CalcSizeVirtual+0x166
04 000000ea2e6980c0 00007ffb4806969e mshtml!CLayout::CalcSize+0x247
05 000000ea2e698270 00007ffb480694a8 mshtml!CFlowLayout::MeasureSite+0x42b
06 000000ea2e6983f0 00007ffb4806936f mshtml!CFlowLayout::GetSiteWidth+0x123
07 000000ea2e6984a0 00007ffb48069959 mshtml!CLSMeasurer::GetSiteWidth+0xaf
08 000000ea2e698520 00007ffb4806b97b mshtml!CLineServices::VerticalAlignOneObjectFast+0x443
09 000000ea2e6985f0 00007ffb4806ea8a mshtml!CLineServices::VerticalAlignObjectsFast+0x2da
0a 000000ea2e698730 00007ffb483648f0 mshtml!CLSMeasurer::Measure+0x3c6
0b 000000ea2e6987c0 00007ffb48273b4d mshtml!CLSMeasurer::MeasureLine+0x3c
0c 000000ea2e698810 00007ffb4806b01f mshtml!CRecalcLinePtr::MeasureLine+0x2a6
0d 000000ea2e698980 00007ffb4806e3ea mshtml!CDisplay::RecalcLinesWithMeasurer+0x2f2
0e 000000ea2e698ae0 00007ffb4806d555 mshtml!CDisplay::RecalcLines+0x6a
0f 000000ea2e698d20 00007ffb48057c51 mshtml!CDisplay::RecalcView+0x54
10 000000ea2e698d60 00007ffb4803af3d mshtml!CFlowLayout::CalcTextSize+0x303
11 000000ea2e698ed0 00007ffb4805a85d mshtml!CFlowLayout::CalcSizeCoreCompat+0x4a9
12 000000ea2e699440 00007ffb47b13a7f mshtml!CFlowLayout::CalcSizeVirtual+0x89
13 000000ea2e6994d0 00007ffb4806969e mshtml!CLayout::CalcSize+0x247
14 000000ea2e699680 00007ffb480694a8 mshtml!CFlowLayout::MeasureSite+0x42b
15 000000ea2e699800 00007ffb4806936f mshtml!CFlowLayout::GetSiteWidth+0x123
16 000000ea2e6998b0 00007ffb48071555 mshtml!CLSMeasurer::GetSiteWidth+0xaf
17 000000ea2e699930 00007ffb511539fe mshtml!CEmbeddedILSObj::Fmt+0x261
18 000000ea2e699a50 00007ffb51154acf msls31!ProcessOneRun+0x2f1
19 000000ea2e699ba0 00007ffb511544fb msls31!FetchAppendEscCore+0x11f
1a 000000ea2e699ca0 00007ffb511543bf msls31!FiniFormatGeneralCase+0x11b
1b 000000ea2e699d70 00007ffb51153bef msls31!CreateLineCore+0x837
1c 000000ea2e699f10 00007ffb4806e2e7 msls31!LsCreateLine+0x11f
1d 000000ea2e699fa0 00007ffb480727c9 mshtml!CLSMeasurer::LSDoCreateLine+0x1c3
1e 000000ea2e69a170 00007ffb4806ebf8 mshtml!CLSMeasurer::LSMeasure+0x79
1f 000000ea2e69a290 00007ffb483648f0 mshtml!CLSMeasurer::Measure+0x160
20 000000ea2e69a320 00007ffb48273b4d mshtml!CLSMeasurer::MeasureLine+0x3c
21 000000ea2e69a370 00007ffb4806b01f mshtml!CRecalcLinePtr::MeasureLine+0x2a6
22 000000ea2e69a4e0 00007ffb4806e3ea mshtml!CDisplay::RecalcLinesWithMeasurer+0x2f2
23 000000ea2e69a640 00007ffb4806d555 mshtml!CDisplay::RecalcLines+0x6a
24 000000ea2e69a880 00007ffb48057c51 mshtml!CDisplay::RecalcView+0x54
25 000000ea2e69a8c0 00007ffb4803af3d mshtml!CFlowLayout::CalcTextSize+0x303
26 000000ea2e69aa30 00007ffb4805a85d mshtml!CFlowLayout::CalcSizeCoreCompat+0x4a9
27 000000ea2e69afa0 00007ffb47b13a7f mshtml!CFlowLayout::CalcSizeVirtual+0x89
28 000000ea2e69b030 00007ffb4806969e mshtml!CLayout::CalcSize+0x247
29 000000ea2e69b1e0 00007ffb480694a8 mshtml!CFlowLayout::MeasureSite+0x42b
2a 000000ea2e69b360 00007ffb4806936f mshtml!CFlowLayout::GetSiteWidth+0x123
2b 000000ea2e69b410 00007ffb48069959 mshtml!CLSMeasurer::GetSiteWidth+0xaf
2c 000000ea2e69b490 00007ffb4806b97b mshtml!CLineServices::VerticalAlignOneObjectFast+0x443
2d 000000ea2e69b560 00007ffb4806ea8a mshtml!CLineServices::VerticalAlignObjectsFast+0x2da
2e 000000ea2e69b6a0 00007ffb483648f0 mshtml!CLSMeasurer::Measure+0x3c6
2f 000000ea2e69b730 00007ffb48273b4d mshtml!CLSMeasurer::MeasureLine+0x3c
30 000000ea2e69b780 00007ffb48078d35 mshtml!CRecalcLinePtr::MeasureLine+0x2a6
31 000000ea2e69b8f0 00007ffb48065115 mshtml!CDisplay::RecalcLines+0x51f
32 000000ea2e69c4a0 00007ffb4807ea6c mshtml!CDisplay::UpdateView+0x1cc
33 000000ea2e69c670 00007ffb48059fde mshtml!CFlowLayout::CommitChanges+0xcb
34 000000ea2e69c770 00007ffb4803af3d mshtml!CFlowLayout::CalcTextSize+0x51c
35 000000ea2e69c8e0 00007ffb4805a85d mshtml!CFlowLayout::CalcSizeCoreCompat+0x4a9
36 000000ea2e69ce50 00007ffb47b13a7f mshtml!CFlowLayout::CalcSizeVirtual+0x89
37 000000ea2e69cee0 00007ffb48059e0c mshtml!CLayout::CalcSize+0x247
38 000000ea2e69d090 00007ffb480547b7 mshtml!CFlowLayout::DoLayout+0x461
39 000000ea2e69d200 00007ffb4797eea9 mshtml!CView::ExecuteLayoutTasks+0xe3
3a 000000ea2e69d290 00007ffb4820e9da mshtml!CView::EnsureView+0x43f
3b 000000ea2e69d370 00007ffb48356a72 mshtml!CElement::EnsureRecalcNotify+0xa4
3c 000000ea2e69d3b0 00007ffb47d095ff mshtml!CElement::EnsureRecalcNotify+0x1e
3d 000000ea2e69d3f0 00007ffb47d04046 mshtml!CDisplayPointer::MoveToMarkupPointer+0xaf
3e 000000ea2e69d460 00007ffb47d0446a mshtml!CSelectionManager::CreateTrackerForContext+0x19e
3f 000000ea2e69d500 00007ffb47d0434b mshtml!CSelectionManager::SetEditContext+0xe6
40 000000ea2e69d580 00007ffb47d04e65 mshtml!CSelectionManager::SetEditContextFromElement+0x18b
41 000000ea2e69d670 00007ffb47d07764 mshtml!CSelectionManager::SetInitialEditContext+0x45
42 000000ea2e69d6b0 00007ffb47d086bc mshtml!CSelectionManager::Initialize+0x2a8
43 000000ea2e69d6e0 00007ffb47a45272 mshtml!CHTMLEditor::Initialize+0x15c
44 000000ea2e69d760 00007ffb47cefa20 mshtml!CDoc::GetHTMLEditor+0x11a
45 000000ea2e69d7a0 00007ffb47c43116 mshtml!CElement::InjectInternal+0x807
46 000000ea2e69d960 00007ffb47cc5b29 mshtml!CElement::InjectTextOrHTML+0x38d
47 000000ea2e69da40 00007ffb47d4fc7d mshtml!CElement::put_innerText+0x29
48 000000ea2e69da80 00007ffb47c48429 mshtml!GS_BSTR+0x12b
49 000000ea2e69daf0 00007ffb47cdfed0 mshtml!CBase::ContextInvokeEx+0x658
4a 000000ea2e69dc10 00007ffb4820d0bd mshtml!CElement::VersionedInvokeEx+0xb7
4b 000000ea2e69dcc0 00007ffb465fa1e4 mshtml!CBase::PrivateInvokeEx+0x179
4c 000000ea2e69dd40 00007ffb466df12e jscript9!HostDispatch::CallInvokeEx+0x1b6
4d 000000ea2e69de10 00007ffb466df05b jscript9!HostDispatch::PutValueByDispId+0xb6
4e 000000ea2e69ded0 00007ffb466df00f jscript9!HostDispatch::PutValue+0x37
4f 000000ea2e69df10 00007ffb46734757 jscript9!HostDispatch::SetPropertyCore+0x6a
50 000000ea2e69df40 00007ffb4656420c jscript9!Js::JavascriptOperators::OP_SetProperty+0x2f8
51 000000ea2e69dfd0 00007ffb465644a2 jscript9!Js::JavascriptOperators::PatchPutValueNoFastPath+0x80
52 000000ea2e69e050 00007ffb4650e240 jscript9!Js::InterpreterStackFrame::Process+0x5553
53 000000ea2e69e390 000000ea217d0ddb jscript9!Js::InterpreterStackFrame::InterpreterThunk<1>+0x386
54 000000ea2e69e680 00007ffb46509eb3 js!CPrintDoc_RectComplete [res://ieframe.dll/preview.js # 2660,1]
55 000000ea2e69e6b0 00007ffb4672ae52 jscript9!amd64_CallFunction+0x93
56 000000ea2e69e710 00007ffb4650e240 jscript9!Js::InterpreterStackFrame::Process+0x1071
57 000000ea2e69ea50 000000ea217d0dfb jscript9!Js::InterpreterStackFrame::InterpreterThunk<1>+0x386
58 000000ea2e69ec90 00007ffb46509eb3 js!OnRectCompleteNext [res://ieframe.dll/preview.js # 742,1]
59 000000ea2e69ecc0 00007ffb4672ae52 jscript9!amd64_CallFunction+0x93
5a 000000ea2e69ed30 00007ffb4650e240 jscript9!Js::InterpreterStackFrame::Process+0x1071
5b 000000ea2e69f070 000000ea217d0de3 jscript9!Js::InterpreterStackFrame::InterpreterThunk<1>+0x386
5c 000000ea2e69f2e0 00007ffb46509eb3 js!anonymous [Unknown script code # 1,1]
5d 000000ea2e69f310 00007ffb46509af1 jscript9!amd64_CallFunction+0x93
5e 000000ea2e69f360 00007ffb46509cfe jscript9!Js::JavascriptFunction::CallFunction<1>+0x6d
5f 000000ea2e69f3a0 00007ffb46509dff jscript9!Js::JavascriptFunction::CallRootFunction+0x110
60 000000ea2e69f480 00007ffb46509d58 jscript9!ScriptSite::CallRootFunction+0x63
61 000000ea2e69f4e0 00007ffb46623c42 jscript9!ScriptSite::Execute+0x122
62 000000ea2e69f570 00007ffb46658594 jscript9!JavascriptDispatch::InvokeOnSelf+0x102
63 000000ea2e69f5f0 00007ffb466586ab jscript9!JavascriptDispatch::InvokeEx+0x1e4
64 000000ea2e69f700 00007ffb480d43a9 jscript9!JavascriptDispatch::Invoke+0x7b
65 000000ea2e69f750 00007ffb47c84e73 mshtml!CWindow::ExecuteCallbackScript+0x144
66 000000ea2e69f8d0 00007ffb4797e57e mshtml!CWindow::FireTimeOut+0x295
67 000000ea2e69f960 00007ffb486236a1 mshtml!CPaintBeat::ProcessTimers+0x327
68 000000ea2e69fa00 00007ffb47a45ee9 mshtml!CPaintBeat::OnWMTimer+0x61
69 000000ea2e69fa30 00007ffb4796e166 mshtml!FormsOnTimer+0x9f
6a 000000ea2e69fa80 00007ffb7ad324fd mshtml!GlobalWndProc+0x1c6
6b 000000ea2e69fb00 00007ffb7ad32357 user32!UserCallWinProcCheckWow+0x149
6c 000000ea2e69fbd0 00007ffb48667b84 user32!DispatchMessageWorker+0x1a7
6d 000000ea2e69fc50 00007ffb785513f2 mshtml!ModelessThreadProc+0x1c4
6e 000000ea2e69fce0 00007ffb7aec54f4 kernel32!BaseThreadInitThunk+0x22
6f 000000ea2e69fd10 0000000000000000 ntdll!RtlUserThreadStart+0x34

fx509Certificate error: Certificate public key does NOT match stored keyset

I'm in need of some serious certificate god intervention. I'm using BouncyCastle csharp to generate a CA and SSL self signed certificate. Below is the code that generates the certificates:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Downloaded using nuget, source: http://www.bouncycastle.org/csharp/
//Library is open-source.
namespace CertificateToolLibrary
{
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.X509.Extension;
using Org.BouncyCastle.X509;
public class X509Certificate2Builder
{
public string SubjectName
{ set { _subjectName = value; }
get { return _subjectName; }
}
public string SubjectAlternativeName
{ set { _subjectAlternativeName = value; }
get { return _subjectAlternativeName; }
}
public string IssuerName
{ set { _issuerName = value; }
get { return _issuerName; }
}
public AsymmetricAlgorithm IssuerPrivateKey
{ set { _issuerPrivateKey = value; }
get { return _issuerPrivateKey; }
}
public X509Certificate2 Issuer
{
set
{
_issuer = value;
_issuerName = value.IssuerName.Name;
if (value.HasPrivateKey)
_issuerPrivateKey = value.PrivateKey;
}
get { return _issuer; }
}
public int? KeyStrength
{ set { _keyStrength = value ?? 2048; }
get { return _keyStrength; }
}
public DateTime? NotBefore
{ set { _notBefore = value; }
get { return _notBefore; }
}
public DateTime? NotAfter
{ set { _notAfter = value; }
get { return _notAfter; }
}
public bool Intermediate
{ set { _intermediate = value; }
get { return _intermediate; }
}
private string _subjectName;
private string _subjectAlternativeName;
private X509Certificate2 _issuer;
private string _issuerName;
private AsymmetricAlgorithm _issuerPrivateKey;
private int _keyStrength = 2048;
private DateTime? _notBefore;
private DateTime? _notAfter;
private bool _intermediate = true;
private const string KEY_CONTAINER_NAME = "cf16236d-0e91-4cb7-9670-6cdbafe54c11";
public X509Certificate2 BuildCACert(ref AsymmetricKeyParameter CaPrivateKey)
{
const int keyStrength = 2048;
// Generating Random Numbers
CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
SecureRandom random = new SecureRandom(randomGenerator);
// The Certificate Generator
var certificateGenerator = new X509V3CertificateGenerator();
// Serial Number
BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
certificateGenerator.SetSerialNumber(serialNumber);
// Signature Algorithm
certificateGenerator.SetSignatureAlgorithm("SHA512withRSA");
// Issuer and Subject Name
X509Name subjectDN = new X509Name(_subjectName);
X509Name issuerDN = subjectDN;
certificateGenerator.SetIssuerDN(issuerDN);
certificateGenerator.SetSubjectDN(subjectDN);
// Valid For
certificateGenerator.SetNotBefore(_notBefore ?? DateTime.UtcNow.Date.AddDays(-1));
certificateGenerator.SetNotAfter(_notAfter ?? DateTime.UtcNow.Date.AddYears(5));
//Turn Basic Constraints off to remove the error on scout for mozilla_pkix_error_ca_cert_used_as_end entity error:
//https://bugzilla.mozilla.org/show_bug.cgi?id=1034124
// Basic Constraints - certificate is allowed to be used as intermediate.
certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(_intermediate));
//Key Usage(s)
certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.CrlSign | KeyUsage.KeyCertSign));
// Subject Public Key
AsymmetricCipherKeyPair subjectKeyPair;
KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
keyPairGenerator.Init(keyGenerationParameters);
subjectKeyPair = keyPairGenerator.GenerateKeyPair();
certificateGenerator.SetPublicKey(subjectKeyPair.Public);
// Generating the Certificate
AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;
// selfsign certificate
Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);
X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
CaPrivateKey = issuerKeyPair.Private;
return x509;
}
public X509Certificate2 BuildSelfSignedCert(AsymmetricKeyParameter issuerPrivKey)
{
const int keyStrength = 2048;
// Generating Random Numbers
var randomGenerator = new CryptoApiRandomGenerator();
var random = new SecureRandom(randomGenerator);
// The Certificate Generator
var certificateGenerator = new X509V3CertificateGenerator();
// Serial Number
var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);
certificateGenerator.SetSerialNumber(serialNumber);
// Signature Algorithm
certificateGenerator.SetSignatureAlgorithm("SHA512withRSA");
// Issuer and Subject Name
certificateGenerator.SetIssuerDN(new X509Name(_issuerName ?? _subjectName));
certificateGenerator.SetSubjectDN(new X509Name(_subjectName));
//Subject Alternative Name
if (!(String.IsNullOrEmpty(_subjectAlternativeName)))
{
//IP Addresss
GeneralNames dnsAltName = new GeneralNames(new GeneralName[] { new GeneralName(GeneralName.IPAddress, _subjectAlternativeName), new GeneralName(GeneralName.DnsName, _subjectAlternativeName) });
//certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);
certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, dnsAltName);
}
// Valid For
certificateGenerator.SetNotBefore(_notBefore ?? DateTime.UtcNow.Date.AddDays(-1));
certificateGenerator.SetNotAfter(_notAfter ?? DateTime.UtcNow.Date.AddYears(5));
// Basic Constraints - SSL certificate not allowed to be used as intermediate.
certificateGenerator.AddExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false));
// Authority Key Identifier
var authorityKeyIdentifier = new AuthorityKeyIdentifierStructure(DotNetUtilities.FromX509Certificate(_issuer));
certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifier);
//Key Usage(s)
certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.NonRepudiation | KeyUsage.KeyEncipherment | KeyUsage.DataEncipherment));
//Extended Key Usage(s)
var usages = new[] { KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth };
certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(usages));
// Subject Public Key
AsymmetricCipherKeyPair subjectKeyPair;
var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
var keyPairGenerator = new RsaKeyPairGenerator();
keyPairGenerator.Init(keyGenerationParameters);
subjectKeyPair = keyPairGenerator.GenerateKeyPair();
certificateGenerator.SetPublicKey(subjectKeyPair.Public);
// Generating the Certificate
AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;
// selfsign certificate
Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(issuerPrivKey, random);
// corresponding private key
PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
// merge into X509Certificate2
X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
if (seq.Count != 9)
{
throw new PemException("malformed sequence in RSA private key");
}
RsaPrivateKeyStructure rsa = new RsaPrivateKeyStructure(seq);
RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);
x509.PrivateKey = ToDotNetKey(rsaparams);
return x509;
}
public static AsymmetricAlgorithm ToDotNetKey(RsaPrivateCrtKeyParameters privateKey)
{
var cspParams = new CspParameters
{
ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider",
ProviderType = 24,
KeyContainerName = KEY_CONTAINER_NAME,
KeyNumber = (int)KeyNumber.Signature,
Flags = CspProviderFlags.UseMachineKeyStore
};
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams);
RSAParameters parameters = new RSAParameters
{
Modulus = privateKey.Modulus.ToByteArrayUnsigned(),
P = privateKey.P.ToByteArrayUnsigned(),
Q = privateKey.Q.ToByteArrayUnsigned(),
DP = privateKey.DP.ToByteArrayUnsigned(),
DQ = privateKey.DQ.ToByteArrayUnsigned(),
InverseQ = privateKey.QInv.ToByteArrayUnsigned(),
D = privateKey.Exponent.ToByteArrayUnsigned(),
Exponent = privateKey.PublicExponent.ToByteArrayUnsigned()
};
rsaProvider.ImportParameters(parameters);
return rsaProvider;
}
}
}
And then, the calling code:
AsymmetricKeyParameter myCAprivateKey = null;
//CA Certificate Actions
ca2 = new X509Certificate2Builder { SubjectName = "CN=Test Certificate Authority" }.BuildCACert(ref myCAprivateKey);
X509Store castore = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
castore.Open(OpenFlags.ReadWrite | OpenFlags.MaxAllowed);
castore.Add(ca2);
castore.Close();
//build out the file name.
string localCAFile = txtPFXExport.Text + "\\TestCertificateAuthority.cer";
//export CA cert to desktop.
TestCertificateCreationUtility.Program.ExportCertificateToFileSystem(ca2, localCAFile, false, txtPFXPass.Text);
//SSL Certificate Actions
var cert2 = new X509Certificate2Builder { SubjectName = "CN=" + txtCNAME.Text, SubjectAlternativeName = txtSAN.Text, Issuer = ca2, Intermediate = true }.BuildSelfSignedCert(myCAprivateKey);
//build out the file name.
string localPFXFile = txtPFXExport.Text + "\\" + txtCNAME.Text + ".pfx";
However, when i run certutil -v -store MY, i'm getting:
================ Certificate 0 ================
X509 Certificate:
Version: 3
Serial Number: 6b1ccf343b18c7e7
Signature Algorithm:
Algorithm ObjectId: 1.2.840.113549.1.1.13 sha512RSA
Algorithm Parameters:
05 00
Issuer:
CN=Test Certificate Authority
Name Hash(sha1): e63af6f08c0a4f2e190c7bc1a406ac57e167b460
Name Hash(md5): a2f27838878e6ae3df34ed2d9b970a2d
NotBefore: 11/15/2016 7:00 PM
NotAfter: 11/16/2021 7:00 PM
Subject:
CN=10.13.206.99
Name Hash(sha1): ee5776f520e749311a56a44a5b7b15d9ffb5e678
Name Hash(md5): 187b17b18c208ad942b23763d5feacd7
Public Key Algorithm:
Algorithm ObjectId: 1.2.840.113549.1.1.1 RSA
Algorithm Parameters:
05 00
Public Key Length: 2048 bits
Public Key: UnusedBits = 0
0000 30 82 01 0a 02 82 01 01 00 ae 12 4d 4d 4a d8 e9
0010 f8 77 9b 2e 29 1f 94 04 d1 8c 59 2b 62 05 1a 9c
0020 0c 2a f7 62 28 ce bd 0d 44 35 18 01 8e 43 56 7b
0030 82 6f 81 79 65 fa 7b c6 1b a4 f2 21 c3 bb 14 cb
0040 79 90 5a 4e b2 fc 37 91 3d cb fe c1 a4 13 df 02
0050 2e f4 da 01 6a bd d2 59 eb af 18 3d 02 36 a6 d4
0060 9d 2a 41 72 d4 da f3 65 9c 78 f0 2a 63 df 38 a7
0070 4d cd 7a 78 67 cb 37 87 52 55 8d 68 4b 5a 7a eb
0080 32 b4 d3 de f4 67 9a 34 8a db 85 b5 bd 55 9f 99
0090 72 53 d3 92 85 aa b6 16 87 83 e0 59 11 64 e1 79
00a0 d9 03 a0 07 bd 1e cd 40 68 ec d2 06 ce 6f 88 31
00b0 34 c9 a5 34 90 fa 0c bd 50 7f fd 67 df 92 69 f5
00c0 f2 62 0c c2 f6 2a 94 62 dd 97 db 01 71 2b aa 78
00d0 3f a7 94 ba 70 e0 d3 cb d8 ae f3 87 8b c1 35 5e
00e0 e7 1d b8 00 fc 34 db 75 f0 ad b6 67 ac 6f 81 f7
00f0 6a 63 3c d3 1b f7 18 5d 83 ad 58 c1 79 2f 4a 56
0100 3e e6 3a a4 a3 94 0c 37 a5 02 03 01 00 01
Certificate Extensions: 4
2.5.29.19: Flags = 0, Length = 2
Basic Constraints
Subject Type=End Entity
Path Length Constraint=None
2.5.29.35: Flags = 0, Length = 4e
Authority Key Identifier
KeyID=a5 25 a6 c6 bf 95 07 31 0f 85 cf cc b6 0a da 16 92 f0 85 47
Certificate Issuer:
Directory Address:
CN=Test Certificate Authority
Certificate SerialNumber=11 c6 33 31 b9 42 f1 7d
2.5.29.15: Flags = 1(Critical), Length = 4
Key Usage
Digital Signature, Non-Repudiation, Key Encipherment, Data Encipherment (f0)
2.5.29.37: Flags = 0, Length = 16
Enhanced Key Usage
Client Authentication (1.3.6.1.5.5.7.3.2)
Server Authentication (1.3.6.1.5.5.7.3.1)
Signature Algorithm:
Algorithm ObjectId: 1.2.840.113549.1.1.13 sha512RSA
Algorithm Parameters:
05 00
Signature: UnusedBits=0
0000 e4 0a d2 00 0f 95 6b 8e b8 bd da ff 7d 54 5c b4
0010 d0 13 39 de 53 35 91 dd eb c5 0c 9f 1b 65 01 eb
0020 68 ad 0e b9 cc 4f 11 64 f0 30 49 95 30 5f de 4a
0030 d7 ec c6 22 db 33 c4 7e 50 d7 fc 79 1d 8c 9c 40
0040 18 9d 3b 7d 68 3d c1 51 ad e3 30 99 62 cf 5a 7a
0050 c3 fb 98 06 40 0f 2f 38 60 dd 6e 22 d5 9c df 94
0060 71 c3 a7 c9 80 1d 68 a0 59 e2 89 a6 c2 b5 9a 69
0070 c4 0a 27 d3 80 a5 77 9e 15 c6 da 79 c1 99 7a c4
0080 e7 b8 77 b6 db f8 1d c7 b9 7c 80 de 66 ac e7 38
0090 09 24 0a c5 f9 95 cd 01 0f 23 3d 2c 8f 07 5f 8e
00a0 de e2 50 2e 54 44 72 76 f6 1f 64 d2 bf 47 39 98
00b0 08 79 87 7b f0 c3 c0 bb 69 1d f3 97 1f ab 70 d1
00c0 d7 5b ee 18 08 fc e6 a2 92 73 28 65 98 6e 45 36
00d0 59 8d 37 78 83 e8 80 6b 66 cc ae 49 14 2c 28 11
00e0 29 b3 b3 22 81 b7 27 d7 33 84 d7 75 8c 4d 90 c4
00f0 11 5b c2 11 9b f6 f1 5d d3 6a 04 e1 65 4e 49 69
Non-root Certificate
Key Id Hash(rfc-sha1): cd a7 52 88 42 30 3b f8 9d bf 05 cd 05 52 f8 fa 22 36 8f 48
Key Id Hash(sha1): 2a 62 63 b4 80 89 57 d0 bb a1 ac 34 1e 06 f0 45 7f 92 61 07
Key Id Hash(md5): 595eb604a64cea82117caae36148fbfd
Key Id Hash(sha256): 0df22d23712b109af3cce45abe23ea6f666e756dad3c2b6dbffad05946fefcbf
Cert Hash(md5): dd 7e 1a 00 10 30 67 c7 b9 1e 5f ea b0 09 c3 6e
Cert Hash(sha1): 87 d4 8c 1d 52 44 10 d9 ff 71 9f c8 31 80 20 34 d6 82 03 94
Cert Hash(sha256): 81ab6f802ed270f184d2e96fbd0e34953a228c5185f0812574b3373048882edf
Signature Hash: f4b1c5cba4228969ccdccd237078ace1e249673edcf2465cd399a0a14bf64ee47ebf4a9feb062c504b95772eebcab9a89eeeced558f42788876add2ce0b5531c
CERT_MD5_HASH_PROP_ID(4):
dd 7e 1a 00 10 30 67 c7 b9 1e 5f ea b0 09 c3 6e
CERT_SHA1_HASH_PROP_ID(3):
87 d4 8c 1d 52 44 10 d9 ff 71 9f c8 31 80 20 34 d6 82 03 94
CERT_KEY_PROV_INFO_PROP_ID(2):
Key Container = {6E928910-36B1-4C1A-8B72-CF33D5C85C98}
Unique container name: 5619e9cf0e097e0aa54f3dcfec6a06c7_521b1f9c-0dde-4e20-b00f-1cf68cd6e71b
Provider = Microsoft Enhanced RSA and AES Cryptographic Provider
ProviderType = 18
Flags = 20 (32)
CRYPT_MACHINE_KEYSET -- 20 (32)
KeySpec = 2 -- AT_SIGNATURE
CERT_KEY_IDENTIFIER_PROP_ID(20):
2a 62 63 b4 80 89 57 d0 bb a1 ac 34 1e 06 f0 45 7f 92 61 07
Provider = Microsoft Enhanced RSA and AES Cryptographic Provider
ProviderType = 18
Unique container name: 5619e9cf0e097e0aa54f3dcfec6a06c7_521b1f9c-0dde-4e20-b00f-1cf68cd6e71b
RSA
PP_KEYSTORAGE = 1
CRYPT_SEC_DESCR -- 1
KP_PERMISSIONS = 3f (63)
CRYPT_ENCRYPT -- 1
CRYPT_DECRYPT -- 2
CRYPT_EXPORT -- 4
CRYPT_READ -- 8
CRYPT_WRITE -- 10 (16)
CRYPT_MAC -- 20 (32)
D:AI(A;ID;GAGR;;;S-1-5-21-3932969098-2735528041-405945392-1012)(A;ID;GR;;;WD)(A;ID;GAGR;;;BA)
Allow Full Control TEST\Test
Allow Read Everyone
Allow Full Control BUILTIN\Administrators
Certificate Public Key:
Version: 3
Public Key Algorithm:
Algorithm ObjectId: 1.2.840.113549.1.1.1 RSA
Algorithm Parameters:
05 00
Public Key Length: 2048 bits
Public Key: UnusedBits = 0
0000 30 82 01 0a 02 82 01 01 00 ae 12 4d 4d 4a d8 e9
0010 f8 77 9b 2e 29 1f 94 04 d1 8c 59 2b 62 05 1a 9c
0020 0c 2a f7 62 28 ce bd 0d 44 35 18 01 8e 43 56 7b
0030 82 6f 81 79 65 fa 7b c6 1b a4 f2 21 c3 bb 14 cb
0040 79 90 5a 4e b2 fc 37 91 3d cb fe c1 a4 13 df 02
0050 2e f4 da 01 6a bd d2 59 eb af 18 3d 02 36 a6 d4
0060 9d 2a 41 72 d4 da f3 65 9c 78 f0 2a 63 df 38 a7
0070 4d cd 7a 78 67 cb 37 87 52 55 8d 68 4b 5a 7a eb
0080 32 b4 d3 de f4 67 9a 34 8a db 85 b5 bd 55 9f 99
0090 72 53 d3 92 85 aa b6 16 87 83 e0 59 11 64 e1 79
00a0 d9 03 a0 07 bd 1e cd 40 68 ec d2 06 ce 6f 88 31
00b0 34 c9 a5 34 90 fa 0c bd 50 7f fd 67 df 92 69 f5
00c0 f2 62 0c c2 f6 2a 94 62 dd 97 db 01 71 2b aa 78
00d0 3f a7 94 ba 70 e0 d3 cb d8 ae f3 87 8b c1 35 5e
00e0 e7 1d b8 00 fc 34 db 75 f0 ad b6 67 ac 6f 81 f7
00f0 6a 63 3c d3 1b f7 18 5d 83 ad 58 c1 79 2f 4a 56
0100 3e e6 3a a4 a3 94 0c 37 a5 02 03 01 00 01
Key Id Hash(rfc-sha1): cd a7 52 88 42 30 3b f8 9d bf 05 cd 05 52 f8 fa 22 36 8f 48
Key Id Hash(sha1): 2a 62 63 b4 80 89 57 d0 bb a1 ac 34 1e 06 f0 45 7f 92 61 07
Container Public Key:
Public Key Algorithm:
Algorithm ObjectId: 1.2.840.113549.1.1.1 RSA
Algorithm Parameters: NULL
Public Key Length: 1024 bits
Public Key: UnusedBits = 0
0000 30 81 89 02 81 81 00 a2 66 92 2b 96 67 60 b5 2d
0010 c9 34 ed ec 1f 51 d2 24 98 59 de f4 3c 47 bd 84
0020 a3 49 5d d9 a6 a7 33 86 b8 36 d7 02 f5 c0 e9 65
0030 84 b8 7b 65 76 3c f9 b7 74 9a 16 3d 6f 5f 23 0d
0040 fe 67 b7 47 a2 ab 4c e3 0b ee 17 19 e1 21 8a 8a
0050 6a df 65 2b 9d 8c 50 cf ac 0d af 0f d4 64 b5 58
0060 4b a5 63 ea 6f 90 84 a9 92 ac 2e fe 0f cc e4 46
0070 e1 de b6 e6 3d ce 5a 72 af 28 39 23 65 35 42 01
0080 5f ce 90 9f 52 1a 79 02 03 01 00 01
Key Id Hash(rfc-sha1): 1a 77 b0 aa 49 b1 fe d0 93 d6 dc e2 64 ed 34 62 0c 09 da da
Key Id Hash(sha1): 9e 60 9d fc b2 f1 ef 16 d2 7e 5a bc de 51 e1 ab 63 24 eb 67
ERROR: Certificate public key does NOT match stored keyset
Signature test FAILED
CertUtil: -store command completed successfully.
The key part of that verification being: ERROR: Certificate public key does NOT match stored keyset
Signature test FAILED
Does anyone have any idea why this is failing? I'm just trying to get it to pass. I'm really at my wits end on this as if you google "ERROR: Certificate public key does NOT match stored keyset" or "Signature test FAILED" there is exceedingly little information out there on programmatic solutions to this issue.
Any help is HUGELY appreciated. Thank you.
Ok, found the answer. This code, using the BouncyCastle 1.8.1 csharp library will generate a CA certificate and a self-signed certificate.
The invoking code:
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CertificateToolLibrary;
using System.Net.Sockets;
using System.Security.Principal;
using System.Security.Cryptography;
using Microsoft.Win32;
using System.Security.AccessControl;
using SecureString = System.Security.SecureString;
using System.Security.Cryptography.X509Certificates;
using System.Configuration;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
X509Certificate2 ca2 = null;
AsymmetricKeyParameter myCAprivateKey = null;
AsymmetricKeyParameter myCApubKey = null;
//CA Certificate Actions
ca2 = new X509Certificate2Builder { SubjectName = "Test-Certificate-Authority" }.BuildCACert(ref myCApubKey, ref myCAprivateKey);
X509Store castore = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
castore.Open(OpenFlags.ReadWrite | OpenFlags.MaxAllowed);
castore.Add(ca2);
castore.Close();
//build out the file name.
string localCAFile = txtPFXExport.Text + "\\TestCertificateAuthority.cer";
//export CA cert to desktop.
TestCertificateCreationUtility.Program.ExportCertificateToFileSystem(ca2, localCAFile, false, "password");
//SSL Certificate Actions
var cert2 = new X509Certificate2Builder { SubjectName = txtCNAME.Text, SubjectAlternativeName = txtSAN.Text, Issuer = ca2 }.BuildSelfSignedCert(ca2, myCApubKey, myCAprivateKey);
//build out the file name.
string localPFXFile = txtPFXExport.Text + "\\" + txtCNAME.Text + ".pfx";
//export SSL cert to desktop.
bool status = TestCertificateCreationUtility.Program.ExportCertificateToFileSystem(cert2, localPFXFile, true, "password");
The library code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Downloaded using nuget, source: http://www.bouncycastle.org/csharp/
//Library is open-source.
namespace CertificateToolLibrary
{
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.X509.Extension;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Crypto.Operators;
public class X509Certificate2Builder
{
public string SubjectName
{ set { _subjectName = value; }
get { return _subjectName; }
}
public string SubjectAlternativeName
{ set { _subjectAlternativeName = value; }
get { return _subjectAlternativeName; }
}
public string IssuerName
{ set { _issuerName = value; }
get { return _issuerName; }
}
public AsymmetricAlgorithm IssuerPrivateKey
{ set { _issuerPrivateKey = value; }
get { return _issuerPrivateKey; }
}
public X509Certificate2 Issuer
{
set
{
_issuer = value;
_issuerName = value.IssuerName.Name;
if (value.HasPrivateKey)
_issuerPrivateKey = value.PrivateKey;
}
get { return _issuer; }
}
public int? KeyStrength
{ set { _keyStrength = value ?? 2048; }
get { return _keyStrength; }
}
public DateTime? NotBefore
{ set { _notBefore = value; }
get { return _notBefore; }
}
public DateTime? NotAfter
{ set { _notAfter = value; }
get { return _notAfter; }
}
public bool Intermediate
{ set { _intermediate = value; }
get { return _intermediate; }
}
private string _subjectName;
private string _subjectAlternativeName;
private X509Certificate2 _issuer;
private string _issuerName;
private AsymmetricAlgorithm _issuerPrivateKey;
private int _keyStrength = 2048;
private DateTime? _notBefore;
private DateTime? _notAfter;
private bool _intermediate = true;
private const string KEY_CONTAINER_NAME = "cf16236d-0e91-4cb7-9670-6cdbafe54c11";
public X509Certificate2 BuildCACert(ref AsymmetricKeyParameter CaPubKey, ref AsymmetricKeyParameter CaPrivateKey)
{
const int keyStrength = 2048;
// Generating Random Numbers
CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
SecureRandom random = new SecureRandom(randomGenerator);
// The Certificate Generator
X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
// Serial Number
BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
certificateGenerator.SetSerialNumber(serialNumber);
// Signature Algorithm
certificateGenerator.SetSignatureAlgorithm("SHA512withRSA");
// Issuer and Subject Name
X509Name subjectDN = new X509Name("CN=" + _subjectName);
X509Name issuerDN = subjectDN;
certificateGenerator.SetIssuerDN(issuerDN);
certificateGenerator.SetSubjectDN(subjectDN);
// Valid For
certificateGenerator.SetNotBefore(_notBefore ?? DateTime.UtcNow.Date.AddDays(-1));
certificateGenerator.SetNotAfter(_notAfter ?? DateTime.UtcNow.Date.AddYears(5));
//Turn Basic Constraints off to remove the error on scout for mozilla_pkix_error_ca_cert_used_as_end entity error:
//https://bugzilla.mozilla.org/show_bug.cgi?id=1034124
// Basic Constraints - certificate is allowed to be used as intermediate.
certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(_intermediate));
//Key Usage(s)
certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.KeyCertSign));
// Subject Public Key
AsymmetricCipherKeyPair subjectKeyPair;
KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
keyPairGenerator.Init(keyGenerationParameters);
subjectKeyPair = keyPairGenerator.GenerateKeyPair();
certificateGenerator.SetPublicKey(subjectKeyPair.Public);
// Subject Key Identifier
certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(subjectKeyPair.Public));
// Generating the Certificate
AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;
ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);
// corresponding private key
PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
// selfsign certificate
Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded(), string.Empty, X509KeyStorageFlags.Exportable);
Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
if (seq.Count != 9)
{
throw new PemException("malformed sequence in RSA private key");
}
RsaPrivateKeyStructure rsa = new RsaPrivateKeyStructure(seq);
RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);
x509.PrivateKey = ToDotNetKey(rsaparams);
CaPubKey = issuerKeyPair.Public;
CaPrivateKey = issuerKeyPair.Private;
return x509;
}
public X509Certificate2 BuildSelfSignedCert(X509Certificate2 ca ,AsymmetricKeyParameter issuerPubKey, AsymmetricKeyParameter issuerPrivKey)
{
const int keyStrength = 2048;
// Generating Random Numbers
var randomGenerator = new CryptoApiRandomGenerator();
var random = new SecureRandom(randomGenerator);
ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerPrivKey, random);
// The Certificate Generator
var certificateGenerator = new X509V3CertificateGenerator();
// Serial Number
var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);
certificateGenerator.SetSerialNumber(serialNumber);
// Signature Algorithm
certificateGenerator.SetSignatureAlgorithm("SHA512withRSA");
// Issuer and Subject Name
certificateGenerator.SetIssuerDN(new X509Name(_issuerName));
certificateGenerator.SetSubjectDN(new X509Name("CN=" + _subjectName));
//Subject Alternative Name
if (!(String.IsNullOrEmpty(_subjectAlternativeName)))
{
//IP Addresss
GeneralNames dnsAltName = new GeneralNames(new GeneralName[] {
new GeneralName(GeneralName.IPAddress, _subjectName),
new GeneralName(GeneralName.DnsName, _subjectName),
new GeneralName(GeneralName.IPAddress, _subjectAlternativeName),
new GeneralName(GeneralName.DnsName, _subjectAlternativeName),
});
//certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);
certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, dnsAltName);
}
// Valid For
certificateGenerator.SetNotBefore(_notBefore ?? DateTime.UtcNow.Date.AddDays(-1));
certificateGenerator.SetNotAfter(_notAfter ?? DateTime.UtcNow.Date.AddYears(5));
//Key Usage(s)
certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.NonRepudiation | KeyUsage.KeyEncipherment | KeyUsage.DataEncipherment));
//Extended Key Usage(s)
var usages = new[] { KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth };
certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(usages));
// Subject Public Key
AsymmetricCipherKeyPair subjectKeyPair;
var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
var keyPairGenerator = new RsaKeyPairGenerator();
keyPairGenerator.Init(keyGenerationParameters);
subjectKeyPair = keyPairGenerator.GenerateKeyPair();
certificateGenerator.SetPublicKey(subjectKeyPair.Public);
// Generating the Certificate
AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;
// Authority Key Identifier
certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(issuerPubKey));
// Subject Key Identifier
certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(subjectKeyPair.Public));
// selfsign certificate
Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
// corresponding private key
PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
// merge into X509Certificate2
X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded(), string.Empty, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
if (seq.Count != 9)
{
throw new PemException("malformed sequence in RSA private key");
}
RsaPrivateKeyStructure rsa = new RsaPrivateKeyStructure(seq);
RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);
x509.PrivateKey = ToDotNetKey(rsaparams);
return x509;
}
/// <summary>
/// Converts a Bouncy Castle key object into a .NET key object
/// </summary>
/// <param name="privateKey">A bouncy castle key object</param>
/// <returns>A .NET key object</returns>
public static AsymmetricAlgorithm ToDotNetKey(RsaPrivateCrtKeyParameters privateKey)
{
var cspParams = new CspParameters
{
ProviderName = "Microsoft Strong Cryptographic Provider",
ProviderType = 1,
KeyContainerName = Guid.NewGuid().ToString(),
KeyNumber = (int)KeyNumber.Exchange,
Flags = CspProviderFlags.UseMachineKeyStore
};
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams);
RSAParameters parameters = new RSAParameters
{
Modulus = privateKey.Modulus.ToByteArrayUnsigned(),
P = privateKey.P.ToByteArrayUnsigned(),
Q = privateKey.Q.ToByteArrayUnsigned(),
DP = privateKey.DP.ToByteArrayUnsigned(),
DQ = privateKey.DQ.ToByteArrayUnsigned(),
InverseQ = privateKey.QInv.ToByteArrayUnsigned(),
D = privateKey.Exponent.ToByteArrayUnsigned(),
Exponent = privateKey.PublicExponent.ToByteArrayUnsigned()
};
rsaProvider.ImportParameters(parameters);
rsaProvider.PersistKeyInCsp = true;
return rsaProvider;
}
/// <summary>
/// Converts a .NET key object into a Bouncy Castle key object
/// </summary>
/// <param name="privateKey">A .NET key object</param>
/// <param name="isPrivate">True if the key is private, false if it is public</param>
/// <returns>A Bouncy Castle key object</returns>
public static RsaKeyParameters ToBouncyCastleKey(AsymmetricAlgorithm dotNetKey, bool isPrivate)
{
RSACryptoServiceProvider prov = dotNetKey as RSACryptoServiceProvider;
RSAParameters parameters = prov.ExportParameters(isPrivate);
if (isPrivate)
{
return new RsaPrivateCrtKeyParameters(
new BigInteger(1, parameters.Modulus),
new BigInteger(1, parameters.Exponent),
new BigInteger(1, parameters.D),
new BigInteger(1, parameters.P),
new BigInteger(1, parameters.Q),
new BigInteger(1, parameters.DP),
new BigInteger(1, parameters.DQ),
new BigInteger(1, parameters.InverseQ)
);
}
else
{
return new RsaKeyParameters(
false,
new BigInteger(1, parameters.Modulus),
new BigInteger(1, parameters.Exponent)
);
}
}
}
}

Writing a map to an aerospike bin corrupting the aerospike data

I want to write a map bin to aerospike using Java client
The bin should finally look like
{2890:0.75}
and here is my code
HashMap<String, String> newMap = new HashMap<String, String>();
JsonArray infArray = jsonData.get("inferences").getAsJsonArray();
for (int i = 0; i < infArray.size(); i++) {
JsonObject currentInference = infArray.get(i).getAsJsonObject();
String attrId = currentInference.get("attributeId").getAsString();
String weight = currentInference.get("weight").getAsString();
newMap.put(attrId, weight);
}
Bin infBin = new Bin("inferences", Value.get(newMap));
client.put(null, key, infBin);
The issue is when I am writing the bin to aerospike the data is getting corrupted or may be getting encoded whatsoever.
For example the map
(inferences:{0=0, 2890=0.75})
is getting converted to
AC ED 00 05 73 72 00 11 6A 61 76 61 2E 75 74 69 6C 2E 48 61 73 68 4D 61 70 05 07 DA C1 C3 16 60 D1 03 00 02 46 00 0A 6C 6F 61 64 46 61 63 74 6F 72 49 00 09 74 68 72 65 73 68 6F 6C 64 78 70 3F 40 00 00 00 00 00 0C 77 08 00 00 00 10 00 00 00 02 74 00 04 33
I am not sure as to why this is happening. Any help would be of great help as I am totally stuck with this issue. Thanks in advance
Edit1:
Now, there is some interesting thing happening.
I modified the above code as
Bin infBin = new Bin("inferences", Value.getAsMap(newMap));
Also modified the HashMap to use Integer and Double as below
HashMap<Integer, Double> newMap = new HashMap<Integer, Double>();
JsonArray infArray = jsonData.get("inferences").getAsJsonArray();
for (int i = 0; i < infArray.size(); i++) {
JsonObject currentInference = infArray.get(i).getAsJsonObject();
Integer attrId = currentInference.get("attributeId").getAsInt();
Double weight = currentInference.get("weight").getAsDouble();
newMap.put(attrId, weight);
}
Bin infBin = new Bin("inferences", Value.get(newMap));
client.put(null, key, infBin);
Now the first key of the map is getting written correctly to aerospike. But the value is still having the issue.
Then I modified the code again to use Float instead of Double. Then both the keys are getting written correctly of the map are getting written correctly without any issue. But the value is still having the issue.
Then as a final try I modified the Float also as Integer and tried then the aerospike is getting updated properly without any issue. Does this mean that Double and Float are not supported by aerospike Java client?