Wednesday, December 31, 2014

Welcome

Wellcome to "Developer Scripts", here you can find scripts to your sofyware development.
Do not forget add +1 when you use a script published here.

Please visit www.TyroDeveloper.com

Thanks and enjoy the site...

Friday, January 24, 2014

Create a Encrypted Private Key in C#

Whe have this XML Private Key:

5ayPZaKM3flHFu2B7aiYpkI81/cByFHHNSmcgQQfP+X2bIGf7JlkuEneh5z7PRkk7Z05jOGxIMdvDd7pVLIWmgRLWaN7bI8JAVf8lUN0kcjA5KgQNjRI23LpvnvzHQjB4jyNXkhhxKXREreeWtEujduD1u99l5t2WxoDqdbYbdc=

AQAB

/27P2g48qXfQBlFRZ+pes6EBBUYzS3r7B1BL3g/O9VFJnZBPQFzclEdZPVvjh9Ve+HktvbKTaYRJ5wlVewDVRw==

5i8bXxa7g6Tue2/NkOjFK5i54RTaGPbjvPcg1N1Wq8pew0lx0lY3q7A+qH3VjiJHwSRifY7n92zkxutSqF4q8Q== hyilhyZ9ZtblFlK1Fp1nWvlYxuesgMYkSmxsmKYYxqoqn9sadF4uwa83Q0Z6EQgQZr4IPBZf9jdvu3au6pU4RQ== RWDDZjiq0fXfL3M2SUvvScGhnNa1GbsoTydJTP9dhS/cug2j8dqssuHPMOeke0+Xwv4ddWyiO/AlUFNTOY4QcQ== BtvaLLe1E1whaPvvT7r72qPl8oq+E020GiHmvO7v08D1SfynETLs5NJVAn4e3ChHNSvErTshin0r1JvLLTKqRw== 31S3r52rmuEdtnbHI8EQhoLcRSikLBURP2myDGZkuK61u3ckel4CaY0y/O2yBAxiM0fyQULpCTXEkFlUzI3LmKoj/L0cSlk58xf8hB837/fn/bulnATWSajKn/p4ecXpBlPTySf9MPwoyNwXdyjjz0bQc6oo1U42VybQRNgvWGE=
And we need to convert to this format:
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,8c57f58aa0ad5acc

lNc4vhhAiQOJEHuK5Ifc5jA9kLwy082g110hSh81MR4fMfEuUDiu0hanAebaFgA7
vePABXoNJStG9mMO7r+AwSdeZZPF1wpSk35LYNVDZmSp2cy5ZyMDJy+xDNWxYODs
f63i10DWE1/6u+Jlnmq5yWT05PvjBV+Jn/MeMwGgkj3JN8xTc8SgSRDsgarxllpk
YLxF+mUqwnE3JIBASE7W75DjqmI8KfZXaNT9Xp7x1Jyg5h1HTHQnJLCpwmpoGl32
QTWTQw1BuD0gL04VC+nIKPhia16FGyqqD9sGdeCP18tb/yi4Bz8Nlc/ijLjuwFVX
YDoqmjleulNFKQBQcePInStJfDejdETCm30iRhaMe2bH6NJmWfigzlud9uvGsrld
f1QNhyTUS+6ntgbRtKLdhGL5Wx1ZItx5UL9UOl+ho7gJOGwiT7dKcF6zOts9vtre
kkAsNGiXFcpdGC/xnnMoXHgYBUypCcT9D6K1dp7LzJozzACzlWSnhD9HW1lELLb3
AElJP1AwmHnh383qudM2/KoYRyK6VTUmjTUbsPStjmjldvwXqYUt5PVKsTb98JBj
YFafxHdNorg4+ZFY+6JHTIKDMTu+I4td/2ok41oPLAC3x8GVB1iCAG8YgZsKGizy
bbv+H3ns40k8n6XyyzI480Zb7/5PtIzY9tLGA9o2znQ+DWm64Wl2nfRDLfncanO4
EKQoYZVuMfU92TCan4roihURnmkO7YaJg6LeQTHUpkiVajV2Kbpv3JYbHH7Gvs+V
SiSsQlXGirOFY2D82j54P6WT9L/nKtjmjSIZKq/hGPs9JN//XMfIhw==
-----END RSA PRIVATE KEY-----
Here the c# code:
public string EncryptPrivateKey(string pPhrase)
{

    RSA rsa1 = RSA.Create();
    rsa1.FromXmlString(xml_private_key);//Put here your XML Privatye Key
    AsymmetricCipherKeyPair keyPair = 
        Org.BouncyCastle.Security.DotNetUtilities.GetRsaKeyPair(rsa1);
    TextWriter textWriter = new StringWriter();
    PemWriter pemWriter = new PemWriter(textWriter);
    pemWriter.WriteObject(keyPair.Private, "DES-EDE3-CBC", pPhrase.ToCharArray(), new SecureRandom());
    pemWriter.Writer.Flush();
    return (textWriter.ToString());          
}

Wednesday, January 22, 2014

Convert RSA to PEM

Hi friends, after some days searching the way to convert a RSACrytoServiceProvider (RSA) to PEM format finally in C# i found this code:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;

namespace RsaKeyConverter.Converter
{
    public static class RsaKeyConverter
    {
        public static string XmlToPem(string xml)
        {
            using (RSA rsa = RSA.Create())
            {
                rsa.FromXmlString(xml);

                AsymmetricCipherKeyPair keyPair = Org.BouncyCastle.Security.DotNetUtilities.GetRsaKeyPair(rsa); // try get private and public key pair
                if (keyPair != null) // if XML RSA key contains private key
                {
                    PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
                    return FormatPem(Convert.ToBase64String(privateKeyInfo.GetEncoded()), "PRIVATE KEY");
                   
                }

                RsaKeyParameters publicKey = Org.BouncyCastle.Security.DotNetUtilities.GetRsaPublicKey(rsa); // try get public key
                if (publicKey != null) // if XML RSA key contains public key
                {
                    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
                    return FormatPem(Convert.ToBase64String(publicKeyInfo.GetEncoded()), "PUBLIC KEY");
                }
            }

            throw new InvalidKeyException("Invalid RSA Xml Key");
        }

        public static string PublicXmlToPem(string xml)
        {
            using (RSA rsa = RSA.Create())
            {
                rsa.FromXmlString(xml);

                RsaKeyParameters publicKey = Org.BouncyCastle.Security.DotNetUtilities.GetRsaPublicKey(rsa); // try get public key
                if (publicKey != null) // if XML RSA key contains public key
                {
                    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
                    return FormatPem(Convert.ToBase64String(publicKeyInfo.GetEncoded()), "PUBLIC KEY");
                }
            }

            throw new InvalidKeyException("Invalid RSA Xml Key");
        }

        private static string FormatPem(string pem, string keyType)
        {
            var sb = new StringBuilder();
            sb.AppendFormat("-----BEGIN {0}-----\n", keyType);

            int line = 1, width = 64;

            while ((line - 1) * width < pem.Length)
            {
                int startIndex = (line - 1) * width;
                int len = line * width > pem.Length
                              ? pem.Length - startIndex
                              : width;
                sb.AppendFormat("{0}\n", pem.Substring(startIndex, len));
                line++;
            }

            sb.AppendFormat("-----END {0}-----\n", keyType);
            return sb.ToString();
        }

        public static string PemToXml(string pem)
        {
            if (pem.StartsWith("-----BEGIN RSA PRIVATE KEY-----")
                || pem.StartsWith("-----BEGIN PRIVATE KEY-----"))
            {
                return GetXmlRsaKey(pem, obj =>
                {
                    if ((obj as RsaPrivateCrtKeyParameters) != null)
                        return DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)obj);
                    var keyPair = (AsymmetricCipherKeyPair)obj;
                    return DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)keyPair.Private);
                }, rsa => rsa.ToXmlString(true));
            }

            if (pem.StartsWith("-----BEGIN PUBLIC KEY-----"))
            {
                return GetXmlRsaKey(pem, obj =>
                {
                    var publicKey = (RsaKeyParameters)obj;
                    return DotNetUtilities.ToRSA(publicKey);
                }, rsa => rsa.ToXmlString(false));
            }

            throw new InvalidKeyException("Unsupported PEM format...");
        }

        private static string GetXmlRsaKey(string pem, Func getRsa, Func getKey)
        {
            using (var ms = new MemoryStream())
            using (var sw = new StreamWriter(ms))
            using (var sr = new StreamReader(ms))
            {
                sw.Write(pem);
                sw.Flush();
                ms.Position = 0;
                var pr = new PemReader(sr);
                object keyPair = pr.ReadObject();
                using (RSA rsa = getRsa(keyPair))
                {
                    var xml = getKey(rsa);
                    return xml;
                }
            }
        }
    }
}
How to Use:
string private_pem = RsaKeyConverter.Converter.RsaKeyConverter.XmlToPem(rsa.ToXmlString(true));//private
string public_pem = RsaKeyConverter.Converter.RsaKeyConverter.PublicXmlToPem(rsa.ToXmlString(false));//public
Where rsa is your RSACryptoServiceProvider object.

You need C# Bouncy Castle Library - Download is 100% free

Regards