2009-07-22 136 views
7

Sé que esta es una pregunta similar a this one pero antes de seguir por la ruta del Bouncey Castle, alguien sabe si es posible cargar un RSA KeyPair desde un .pem, por ejemplo:Desencriptando con clave privada del archivo .pem en C# con .NET crypto library

-----BEGIN RSA PRIVATE KEY----- 
MIIBOgIBAAJBALKzy66nRuof8Fg0ItatyHS9RiDIKH0m5lorKzKn4y5wR6BXpVUv 
ZwnevrAJWBd6EPr/lcV3hjObxD6+q9vmN8ECAwEAAQJAGNcxWwfZrbXe3QPyS9FA 
aindU7U/G5aKssIJcTMxO0UYpGU+WArJbboKeEIE7bpNfhDOKTL7ZL6kWBR1Svlh 
WQIhAOhtx+xXuSrIot59tmXZaypBDjA4n+Xare0ObFLQxWuvAiEAxNMwm6w33bVr 
FHS9slkOh59Le2mgs0uNT6perHaRP48CIGMyRzrlDY/m5SvTtz6slgIIlceawxNU 
Sxp7J1wI4djdAiA6+BchHNjkCP2a9Fr9OydaRMSFpiDqduFQk/enbiKYSwIhANO3 
SQ51oLFtWN9gX3tfKTXflyO6BV8rgPo980d9CEsb 
-----END RSA PRIVATE KEY----- 

directamente con la biblioteca de criptografía NET 3.5 sin tener que ir a una tercera parte o rodar mi propia?

+0

@CraigMcQueen buena pregunta ... por error, creo. –

Respuesta

11

http://www.jensign.com/opensslkey/index.html

con fuente en http://www.jensign.com/opensslkey/opensslkey.cs

edición: extraído código relevante:

en primer lugar, extraer el texto entre el ---- ---- COMIENZO y FIN ---- - --- secciones, y en base 64 de decodificación en una matriz de bytes (ver enlace anterior para más detalles), y luego pasarlo a:

//------- Parses binary ans.1 RSA private key; returns RSACryptoServiceProvider --- 
public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) 
{ 
    byte[] MODULUS, E, D, P, Q, DP, DQ, IQ ; 

// --------- Set up stream to decode the asn.1 encoded RSA private key ------ 
    MemoryStream mem = new MemoryStream(privkey) ; 
    BinaryReader binr = new BinaryReader(mem) ; //wrap Memory Stream with BinaryReader for easy reading 
    byte bt = 0; 
    ushort twobytes = 0; 
    int elems = 0; 
    try { 
     twobytes = binr.ReadUInt16(); 
     if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) 
      binr.ReadByte(); //advance 1 byte 
     else if (twobytes == 0x8230) 
      binr.ReadInt16(); //advance 2 bytes 
     else 
      return null; 

     twobytes = binr.ReadUInt16(); 
     if (twobytes != 0x0102) //version number 
      return null; 
     bt = binr.ReadByte(); 
     if (bt !=0x00) 
      return null; 


//------ all private key components are Integer sequences ---- 
     elems = GetIntegerSize(binr); 
     MODULUS = binr.ReadBytes(elems); 

     elems = GetIntegerSize(binr); 
     E = binr.ReadBytes(elems) ; 

     elems = GetIntegerSize(binr); 
     D = binr.ReadBytes(elems) ; 

     elems = GetIntegerSize(binr); 
     P = binr.ReadBytes(elems) ; 

     elems = GetIntegerSize(binr); 
     Q = binr.ReadBytes(elems) ; 

     elems = GetIntegerSize(binr); 
     DP = binr.ReadBytes(elems) ; 

     elems = GetIntegerSize(binr); 
     DQ = binr.ReadBytes(elems) ; 

     elems = GetIntegerSize(binr); 
     IQ = binr.ReadBytes(elems) ; 

     Console.WriteLine("showing components .."); 
     if (verbose) { 
      showBytes("\nModulus", MODULUS) ; 
      showBytes("\nExponent", E); 
      showBytes("\nD", D); 
      showBytes("\nP", P); 
      showBytes("\nQ", Q); 
      showBytes("\nDP", DP); 
      showBytes("\nDQ", DQ); 
      showBytes("\nIQ", IQ); 
     } 

// ------- create RSACryptoServiceProvider instance and initialize with public key ----- 
     RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); 
     RSAParameters RSAparams = new RSAParameters(); 
     RSAparams.Modulus =MODULUS; 
     RSAparams.Exponent = E; 
     RSAparams.D = D; 
     RSAparams.P = P; 
     RSAparams.Q = Q; 
     RSAparams.DP = DP; 
     RSAparams.DQ = DQ; 
     RSAparams.InverseQ = IQ; 
     RSA.ImportParameters(RSAparams); 
     return RSA; 
    } 
    catch (Exception) { 
     return null; 
    } 
    finally { 
     binr.Close(); 
    } 
} 
+0

No importa; esa fue la solución de la otra pregunta. – Stobor

+0

Voy a probar esto ... ¿qué quisiste decir que fue la solución para la otra pregunta? La respuesta aceptada a la pregunta a la que hice referencia utilizó la biblioteca Bouncy Castle (que también funciona para mí, por cierto). Solo quiero minimizar mi dependencia de bibliotecas de terceros cuando sea posible. Incluso aquellos con licencias muy generosas. –

+0

@Tim Jarvis: la respuesta principal para la otra pregunta actualmente es "Puede echar un vistazo a la fuente de JavaScience para OpenSSLKey". Es lo mismo que lo que he vinculado y copiado arriba. (BouncyCastle es la respuesta del interrogador por sí mismos, no la respuesta aceptada ...) – Stobor

0

he creado un pequeño hel por paquete NuGet para crear un certificado X509 basado en clave pública y clave privada (rsa).

Consulte NuGet y Github-project para la funcionalidad y ejemplos de código basados ​​en opensslkey.

Cuestiones relacionadas