Skip to content

Commit

Permalink
Address lifetime concerns
Browse files Browse the repository at this point in the history
  • Loading branch information
simonrozsival committed Jun 19, 2024
1 parent b9e78eb commit d93c08e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,23 @@ internal static byte[] X509Encode(SafeX509Handle x)
private static partial IntPtr GetPrivateKeyEntryCertificate(IntPtr privatKeyEntryHandle);
internal static SafeX509Handle GetPrivateKeyEntryCertificate(SafeHandle privatKeyEntryHandle)
{
var certificateHandle = new SafeX509Handle();
var certificatePtr = GetPrivateKeyEntryCertificate(privatKeyEntryHandle.DangerousGetHandle());
Marshal.InitHandle(certificateHandle, Interop.JObjectLifetime.NewGlobalReference(certificatePtr));
return certificateHandle;
bool addedRef = false;
try
{
privatKeyEntryHandle.DangerousAddRef(ref addedRef);
IntPtr certificatePtr = GetPrivateKeyEntryCertificate(privatKeyEntryHandle.DangerousGetHandle());

SafeX509Handle certificateHandle = new();
Marshal.InitHandle(certificateHandle, certificatePtr);
return certificateHandle;
}
finally
{
if (addedRef)
{
privatKeyEntryHandle.DangerousRelease();
}
}
}

[LibraryImport(Libraries.AndroidCryptoNative, EntryPoint = "AndroidCryptoNative_X509DecodeCollection")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,22 @@ public static ICertificatePal FromOtherCert(X509Certificate cert)

AndroidCertificatePal certPal = (AndroidCertificatePal)cert.Pal;

if (certPal._keyStorePrivateKeyEntry is not null)
if (certPal._keyStorePrivateKeyEntry is SafeJObjectHandle privateKeyEntry)
{
var jobjectHandle = new Interop.JObjectLifetime.SafeJObjectHandle();
Marshal.InitHandle(jobjectHandle, Interop.JObjectLifetime.NewGlobalReference(certPal.Handle));
return new AndroidCertificatePal(jobjectHandle);
bool addedRef = false;
try
{
privateKeyEntry.DangerousAddRef(ref addedRef);
SafeJObjectHandle newSafeHandle = SafeJObjectHandle.CreateGlobalReferenceFromHandle(privateKeyEntry.DangerousGetHandle());
return new AndroidCertificatePal(newSafeHandle);
}
finally
{
if (addedRef)
{
privateKeyEntry.DangerousRelease();
}
}
}

// Ensure private key is copied
Expand Down

0 comments on commit d93c08e

Please sign in to comment.