use STM32 crypto library to generate signature - cryptography

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;
}

Related

gcc address sanitizer heap-buffer-overflow error during sort caused by change of condition?

This is the bare-bone version of my function which illustrates the error.
File runtime-error.cpp:
#include <vector>
#include <algorithm>
using namespace std;
int main() {
using vi = vector<int>;
vector<vi> result = {{0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0},
{0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0},
{0}, {0}, {0}, {0}, {0}, {2}, {2}, {2}, {2}, {2},
{2}, {2}, {2}, {2}, {2}, {2}, {2}, {2}, {2}, {2},
{2}, {2}, {2}, {2}, {2}};
sort(result.begin(), result.end(), [](const vi& v1, const vi& v2) {
const auto v10 = v1[0];
const auto v20 = v2[0]; // line 15
return (v10 <= v20); // error condition
// return (v10 < v20); // no error condition
});
return 0;
}
I build it and run it with the following command:
g++ -Wall -g -fsanitize=address -fno-omit-frame-pointer
runtime-error.cpp -o re && ./re
gcc version:
gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1)
if the //no error condition is used, no problem. but as it is, the following error occurs:
==4046513==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x619000000068 at pc 0x55dec650f945 bp 0x7ffc95746530 sp 0x7ffc95746520
READ of size 8 at 0x619000000068 thread T0
#0 0x55dec650f944 in std::vector<int, std::allocator<int> >::operator[](unsigned long) const /usr/include/c++/9/bits/stl_vector.h:1061
#1 0x55dec650851e in operator() ./runtime-error.cpp:15
#2 0x55dec650d424 in operator()<__gnu_cxx::__normal_iterator<std::vector<int>*, std::vector<std::vector<int> > >, __gnu_cxx::__normal_iterator<std::vector<int>*, std::vector<std::vector<int> > > > /usr/include/c++/9/bits/predefined_ops.h:143
#3 0x55dec650d8c1 in __unguarded_partition<__gnu_cxx::__normal_iterator<std::vector<int>*, std::vector<std::vector<int> > >, __gnu_cxx::__ops::_Iter_comp_iter<main()::<lambda(const vi&, const vi&)> > > /usr/include/c++/9/bits/stl_algo.h:1910
#4 0x55dec650c8ed in __unguarded_partition_pivot<__gnu_cxx::__normal_iterator<std::vector<int>*, std::vector<std::vector<int> > >, __gnu_cxx::__ops::_Iter_comp_iter<main()::<lambda(const vi&, const vi&)> > > /usr/include/c++/9/bits/stl_algo.h:1928
#5 0x55dec650c311 in __introsort_loop<__gnu_cxx::__normal_iterator<std::vector<int>*, std::vector<std::vector<int> > >, long int, __gnu_cxx::__ops::_Iter_comp_iter<main()::<lambda(const vi&, const vi&)> > > /usr/include/c++/9/bits/stl_algo.h:1958
#6 0x55dec650c011 in __sort<__gnu_cxx::__normal_iterator<std::vector<int>*, std::vector<std::vector<int> > >, __gnu_cxx::__ops::_Iter_comp_iter<main()::<lambda(const vi&, const vi&)> > > /usr/include/c++/9/bits/stl_algo.h:1973
#7 0x55dec650bd55 in sort<__gnu_cxx::__normal_iterator<std::vector<int>*, std::vector<std::vector<int> > >, main()::<lambda(const vi&, const vi&)> > /usr/include/c++/9/bits/stl_algo.h:4905
#8 0x55dec650aec7 in main ./runtime-error.cpp:13
#9 0x7f42966df082 in __libc_start_main ../csu/libc-start.c:308
#10 0x55dec65083ed in _start (./re+0x13ed)
0x619000000068 is located 24 bytes to the left of 1080-byte region [0x619000000080,0x6190000004b8)
allocated by thread T0 here:
#0 0x7f4296d08587 in operator new(unsigned long) ../../../../src/libsanitizer/asan/asan_new_delete.cc:104
#1 0x55dec65113bf in __gnu_cxx::new_allocator<std::vector<int, std::allocator<int> > >::allocate(unsigned long, void const*) /usr/include/c++/9/ext/new_allocator.h:114
#2 0x55dec6510f2e in std::allocator_traits<std::allocator<std::vector<int, std::allocator<int> > > >::allocate(std::allocator<std::vector<int, std::allocator<int> > >&, unsigned long) /usr/include/c++/9/bits/alloc_traits.h:443
#3 0x55dec6510749 in std::_Vector_base<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >::_M_allocate(unsigned long) /usr/include/c++/9/bits/stl_vector.h:343
#4 0x55dec650fe40 in void std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >::_M_range_initialize<std::vector<int, std::allocator<int> > const*>(std::vector<int, std::allocator<int> > const*, std::vector<int, std::allocator<int> > const*, std::forward_iterator_tag) /usr/include/c++/9/bits/stl_vector.h:1579
#5 0x55dec650f588 in std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >::vector(std::initializer_list<std::vector<int, std::allocator<int> > >, std::allocator<std::vector<int, std::allocator<int> > > const&) /usr/include/c++/9/bits/stl_vector.h:626
#6 0x55dec650a47a in main ./runtime-error.cpp:11
#7 0x7f42966df082 in __libc_start_main ../csu/libc-start.c:308
SUMMARY: AddressSanitizer: heap-buffer-overflow /usr/include/c++/9/bits/stl_vector.h:1061 in std::vector<int, std::allocator<int> >::operator[](unsigned long) const
Shadow bytes around the buggy address:
0x0c327fff7fb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c327fff7fc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c327fff7fd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c327fff7fe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c327fff7ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x0c327fff8000: fa fa fa fa fa fa fa fa fa fa fa fa fa[fa]fa fa
0x0c327fff8010: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c327fff8020: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c327fff8030: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c327fff8040: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c327fff8050: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
Container overflow: fc
Array cookie: ac
Intra object redzone: bb
ASan internal: fe
Left alloca redzone: ca
Right alloca redzone: cb
Shadow gap: cc
==4046513==ABORTING
<= does not conform to the semantics of strict partial ordering while < does.

Mifare DESFire EV1 4K AES authentication issue

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.

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

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)
);
}
}
}
}

Problem with publishing rtmp stream to FMS with librtmp

I'm trying to get video from the webcam and get it encoded and then publish the stream to FMS. and now I'am having a problem when I try to publish RTMP stream to the FMS with librtmp.
My code:
char uri[]="rtmp://127.0.0.1/live/bolton";
r= RTMP_Alloc();
RTMP_Init(r);
RTMP_SetupURL(r, (char*)uri);
r->Link.lFlags |= RTMP_LF_LIVE;
r->Link.lFlags |= RTMP_LF_BUFX;
RTMP_EnableWrite(r);
//RTMP_SetBufferMS(r, bufferTime);
RTMP_Connect(r, NULL);
RTMP_ConnectStream(r,0);
And log:
DEBUG: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
DEBUG: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
DEBUG: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
DEBUG: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
DEBUG: HandShake: Handshaking finished....
DEBUG: RTMP_Connect1, handshaked
DEBUG2: RTMP_SendPacket: fd=768, size=85
DEBUG2: 0000: 03 00 00 00 00 00 55 14 00 00 00 00 ......U.....
DEBUG2: 0000: 02 00 07 63 6f 6e 6e 65 63 74 00 3f f0 00 00 00 ...connect.?....
DEBUG2: 0010: 00 00 00 03 00 03 61 70 70 02 00 04 6c 69 76 65 ......app...live
DEBUG2: 0020: 00 04 74 79 70 65 02 00 0a 6e 6f 6e 70 72 69 76 ..type...nonpriv
DEBUG2: 0030: 61 74 65 00 05 74 63 55 72 6c 02 00 15 72 74 6d ate..tcUrl...rtm
DEBUG2: 0040: 70 3a 2f 2f 31 32 37 2e 30 2e 30 2e 31 2f 6c 69 p://127.0.0.1/li
DEBUG2: 0050: 76 65 00 00 09 ve...
DEBUG: Invoking connect
DEBUG2: RTMP_ReadPacket: fd=768
ERROR: RTMP_ReadPacket, failed to read RTMP packet header
DEBUG2: RTMP_SendPacket: fd=-1, size=307
It seems that RTMP_connect connected correctly, but failes in the function RTMP_ConnectStream, I'm not familiar with the rtmp connect sequence, and it's killing me.
What should I do to find the problems, Thanks very much!
I'm dealing with the same problem, but using librtmp with ffmpeg. If you look in the function RTMP_ReadPacket(), you'll see the error is thrown when trying to read the packet header with the method ReadN():
int
RTMP_ReadPacket(RTMP *r, RTMPPacket *packet)
{
uint8_t hbuf[RTMP_MAX_HEADER_SIZE] = { 0 };
char *header = (char *)hbuf;
int nSize, hSize, nToRead, nChunk;
int didAlloc = FALSE;
RTMP_Log(RTMP_LOGDEBUG2, "%s: fd=%d", __FUNCTION__, r->m_sb.sb_socket);
if (ReadN(r, (char *)hbuf, 1) == 0)
{
RTMP_Log(RTMP_LOGERROR, "%s, failed to read RTMP packet header", __FUNCTION__);
return FALSE;
}
That error only throws if the ReadN returns a 0. I haven't figured out on my end why that's happening yet, though.
I got the same issue in the Visual studio.
It turned out that in the debug mode,librtmp set some handshake value 0 instead of generating random data.
//handshake.h
/* generate random data */
#ifdef _DEBUG
memset(serversig+8, 0, RTMP_SIG_SIZE-8);
#else
ip = (int32_t *)(serversig+8);
for (i = 2; i < RTMP_SIG_SIZE/4; i++)
*ip++ = rand();
#endif
Just make sure generating random data.