Skip to content
This repository was archived by the owner on Oct 14, 2021. It is now read-only.

Commit 77e3a91

Browse files
authored
Adds FromBase64 & ToBase64 to PrivateKey (#37)
1 parent ce938df commit 77e3a91

File tree

2 files changed

+68
-7
lines changed

2 files changed

+68
-7
lines changed
Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
using System.Security;
22
namespace SecurityAPICommons.Commons
33
{
4-
[SecuritySafeCritical]
5-
public class PrivateKey : Key
6-
{
4+
[SecuritySafeCritical]
5+
public class PrivateKey : Key
6+
{
77

8-
}
8+
9+
}
910
}

dotnet/dotnetframework/SecurityAPICommons/Keys/PrivateKeyManager.cs

Lines changed: 63 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
using Org.BouncyCastle.Asn1.Nist;
1818
using SecurityAPICommons.Commons;
1919
using SecurityAPICommons.Utils;
20+
using Org.BouncyCastle.Utilities.Encoders;
2021

2122
namespace SecurityAPICommons.Keys
2223
{
@@ -67,9 +68,68 @@ public bool LoadPKCS12(String privateKeyPath, String alias, String password)
6768
return true;
6869
}
6970

70-
/******** EXTERNAL OBJECT PUBLIC METHODS - END ********/
71-
72-
[SecuritySafeCritical]
71+
[SecuritySafeCritical]
72+
public bool FromBase64(string base64)
73+
{
74+
bool res;
75+
try
76+
{
77+
res = ReadBase64(base64);
78+
}
79+
catch (IOException e)
80+
{
81+
this.error.setError("PK0015", e.Message);
82+
return false;
83+
}
84+
this.hasPrivateKey = res;
85+
return res;
86+
}
87+
88+
[SecuritySafeCritical]
89+
public string ToBase64()
90+
{
91+
if (this.hasPrivateKey)
92+
{
93+
//PrivateKey priKey = getPrivateKeyXML();
94+
//return Base64.toBase64String(priKey.getEncoded());
95+
string encoded = "";
96+
try
97+
{
98+
encoded = Base64.ToBase64String(this.privateKeyInfo.GetEncoded());
99+
}
100+
catch (Exception e)
101+
{
102+
this.error.setError("PK0017", e.Message);
103+
return "";
104+
}
105+
return encoded;
106+
}
107+
this.error.setError("PK0016", "No private key loaded");
108+
return "";
109+
110+
111+
}
112+
113+
/******** EXTERNAL OBJECT PUBLIC METHODS - END ********/
114+
115+
private bool ReadBase64(string base64)
116+
{
117+
byte[] keybytes = Base64.Decode(base64);
118+
Asn1InputStream istream = new Asn1InputStream(keybytes);
119+
Asn1Sequence seq = (Asn1Sequence)istream.ReadObject();
120+
this.privateKeyInfo = PrivateKeyInfo.GetInstance(seq);
121+
istream.Close();
122+
if (this.privateKeyInfo == null)
123+
124+
{
125+
this.error.setError("PK015", "Could not read private key from base64 string");
126+
return false;
127+
}
128+
this.privateKeyAlgorithm = this.privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Id;//this.privateKeyInfo.GetPrivateKeyAlgorithm().getAlgorithm().getId(); // 1.2.840.113549.1.1.1
129+
return true;
130+
}
131+
132+
[SecuritySafeCritical]
73133
public AsymmetricAlgorithm getPrivateKeyForXML()
74134
{
75135

0 commit comments

Comments
 (0)