Ejemplo n.º 1
0
 /// <summary>
 /// Returns true if the given object is the "this" key.
 /// </summary>
 /// <remarks>
 /// The keys are compared by there fingerprint. If the fingerprint
 /// is the same, the keys are said to be the same.
 /// </remarks>
 /// <param name="o">An object that shall be compared against
 /// this.</param>
 /// <returns>True if the giben object o is the same as the
 /// "this" key.</returns>
 public override bool Equals(object o)
 {
     if (o is TransportablePublicKey)
     {
         TransportablePublicKey tpkKey = (TransportablePublicKey)o;
         return(tpkKey.PrimaryKey.Fingerprint == this.PrimaryKey.Fingerprint);
     }
     return(false);
 }
Ejemplo n.º 2
0
        public static TransportablePublicKey[] SplitKeys(string strRadix64)
        {
            ArrayList alKeys = new ArrayList();

            Packet[] pPackets = Packet.ParsePackets(strRadix64);

            byte[] bOneKey = new byte[0];
            for (int i = 0; i < pPackets.Length; i++)
            {
                if (pPackets[i] is PublicKeyPacket)
                {
                    PublicKeyPacket pkpKey = (PublicKeyPacket)pPackets[i];
                    if ((pkpKey.Content == ContentTypes.PublicKey) && (bOneKey.Length > 10))
                    {
                        TransportablePublicKey tpkKey = new TransportablePublicKey(Radix64.Encode(bOneKey, true));
                        alKeys.Add(tpkKey);
                        bOneKey = new byte[0];
                    }
                }
                byte[] bPacket = pPackets[i].Generate();
                byte[] bTmpKey = new byte[bOneKey.Length];
                bOneKey.CopyTo(bTmpKey, 0);
                bOneKey = new byte[bOneKey.Length + bPacket.Length];
                Array.Copy(bTmpKey, 0, bOneKey, 0, bTmpKey.Length);
                Array.Copy(bPacket, 0, bOneKey, bTmpKey.Length, bPacket.Length);
            }

            if (bOneKey.Length > 10)
            {
                TransportablePublicKey tpkKey = new TransportablePublicKey(Radix64.Encode(bOneKey, true));
                alKeys.Add(tpkKey);
            }

            TransportablePublicKey[] tpkKeys = new TransportablePublicKey[alKeys.Count];
            int         iCount = 0;
            IEnumerator ieKeys = alKeys.GetEnumerator();

            while (ieKeys.MoveNext())
            {
                if (!(ieKeys.Current is TransportablePublicKey))
                {
                    continue;
                }

                tpkKeys[iCount++] = (TransportablePublicKey)ieKeys.Current;
            }

            return(tpkKeys);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Verifies the signature of this signed message.
        /// </summary>
        /// <remarks>No remarks</remarks>
        /// <returns>Returns a SignatureStatusType that contains
        /// whether the signature was valid, invalid or could not be
        /// verified</returns>
        /// <param name="pkrKeyRing">The public keyring containing
        /// all keys known to the local system.</param>
        public SignatureStatusTypes Verify(PublicKeyRing pkrKeyRing)
        {
            TransportablePublicKey tpkKey = pkrKeyRing.Find(spSignature.KeyID, true);

            if (tpkKey == null)
            {
                return(SignatureStatusTypes.Signing_Key_Not_Available);
            }

            PublicKeyPacket pkpKey = tpkKey.FindKey(spSignature.KeyID);

            spSignature.Verify(lmSignedMessage.Binary, pkpKey);

            return(spSignature.SignatureStatus);
        }
        public static TransportablePublicKey[] SplitKeys(string strRadix64)
        {
            ArrayList alKeys = new ArrayList();
            Packet[] pPackets = Packet.ParsePackets(strRadix64);

            byte[] bOneKey = new byte[0];
            for (int i=0; i<pPackets.Length; i++) {
                if (pPackets[i] is PublicKeyPacket) {
                    PublicKeyPacket pkpKey = (PublicKeyPacket)pPackets[i];
                    if ((pkpKey.Content == ContentTypes.PublicKey) && (bOneKey.Length > 10)) {
                        TransportablePublicKey tpkKey = new TransportablePublicKey(Radix64.Encode(bOneKey, true));
                        alKeys.Add(tpkKey);
                        bOneKey = new byte[0];
                    }
                }
                byte[] bPacket = pPackets[i].Generate();
                byte[] bTmpKey = new byte[bOneKey.Length];
                bOneKey.CopyTo(bTmpKey, 0);
                bOneKey = new byte[bOneKey.Length + bPacket.Length];
                Array.Copy(bTmpKey, 0, bOneKey, 0, bTmpKey.Length);
                Array.Copy(bPacket, 0, bOneKey, bTmpKey.Length, bPacket.Length);
            }

            if (bOneKey.Length > 10) {
                TransportablePublicKey tpkKey = new TransportablePublicKey(Radix64.Encode(bOneKey, true));
                alKeys.Add(tpkKey);
            }

            TransportablePublicKey[] tpkKeys = new TransportablePublicKey[alKeys.Count];
            int iCount = 0;
            IEnumerator ieKeys = alKeys.GetEnumerator();
            while (ieKeys.MoveNext()) {
                if (!(ieKeys.Current is TransportablePublicKey))
                    continue;

                tpkKeys[iCount++] = (TransportablePublicKey)ieKeys.Current;

            }

            return tpkKeys;
        }
Ejemplo n.º 5
0
        private SymAlgorithms GetSymAlgorithmPreferences(TransportablePublicKey[] tpkKeys)
        {
            bool bCAST5 = true;
            bool bAES256 = true;
            bool bAES192 = true;
            bool bAES128 = true;

            for (int i=0; i< tpkKeys.Length; i++) {
                TransportablePublicKey tpkKey = tpkKeys[i];
                ulong lKeyID = tpkKey.PrimaryKey.KeyID;
                IEnumerator ieCerts = tpkKey.Certifications.GetEnumerator();
                while (ieCerts.MoveNext()) {
                    if (!(ieCerts.Current is CertifiedUserID))
                        continue;

                    CertifiedUserID cuiID = (CertifiedUserID)ieCerts.Current;
                    IEnumerator ieSigs = cuiID.Certificates.GetEnumerator();
                    while (ieSigs.MoveNext()) {
                        if (!(ieSigs.Current is SignaturePacket))
                            continue;

                        SignaturePacket spSig = (SignaturePacket)ieSigs.Current;
                        if ((spSig.Version == SignaturePacketVersionNumbers.v4) && (spSig.KeyID == lKeyID)) {
                            try {
                                bool bTmpCAST5 = false;
                                bool bTmpAES256 = false;
                                bool bTmpAES192 = false;
                                bool bTmpAES128 = false;
                                SymAlgorithms[] saThisKey = spSig.FindPreferedSymAlgorithms();
                                for (int j=0; j<saThisKey.Length; j++) {
                                    if (saThisKey[j] == SymAlgorithms.AES128)
                                        bTmpAES128 = true;
                                    else if (saThisKey[j] == SymAlgorithms.AES192)
                                        bTmpAES192 = true;
                                    else if (saThisKey[j] == SymAlgorithms.AES256)
                                        bTmpAES256 = true;
                                    else if (saThisKey[j] == SymAlgorithms.CAST5)
                                        bTmpCAST5 = true;
                                }

                                if (!bTmpCAST5)
                                    bCAST5 = false;

                                if (!bTmpAES256)
                                    bAES256 = false;

                                if (!bTmpAES192)
                                    bAES192 = false;

                                if (!bTmpAES128)
                                    bAES128 = false;
                            } catch (InvalidOperationException) {}

                        }
                    }
                }
            }
            if (bAES256)
                return SymAlgorithms.AES256;

            if (bAES192)
                return SymAlgorithms.AES192;

            if (bAES128)
                return SymAlgorithms.AES128;

            if (bCAST5)
                return SymAlgorithms.CAST5;

            return SymAlgorithms.Triple_DES;
        }
Ejemplo n.º 6
0
        private byte[] EncryptMessage(Message mToBeEncrypted, ulong[] lTargetKeyIDs)
        {
            CompressedMessage cmMessage = new CompressedMessage();
            cmMessage.Compress(mToBeEncrypted);

            TransportablePublicKey[] tpkSelectedKeys = new TransportablePublicKey[lTargetKeyIDs.Length];
            for (int i=0; i<lTargetKeyIDs.Length; i++)
                tpkSelectedKeys[i] = pkrKeyRing.Find(lTargetKeyIDs[i], true);

            SymAlgorithms saAlgo = GetSymAlgorithmPreferences(tpkSelectedKeys);

            SymmetricallyEncryptedDataPacket sedpEncrypted = new SymmetricallyEncryptedDataPacket();
            SymmetricAlgorithm saEncrypt = CipherHelper.CreateSymAlgorithm(saAlgo);
            saEncrypt.Mode = CipherMode.OpenPGP_CFB;
            saEncrypt.GenerateKey();
            byte[] bKey = saEncrypt.Key;

            ESKSequence esksKeys = new ESKSequence();
            esksKeys = CreateESKSequence(tpkSelectedKeys, AsymActions.Encrypt, saAlgo, bKey);

            ICryptoTransform ictEncryptor = saEncrypt.CreateEncryptor();
            byte[] bMessage = cmMessage.GetEncoded();
            byte[] bOutput = new byte[bMessage.Length];
            ictEncryptor.TransformBlock(bMessage, 0, bMessage.Length, ref bOutput, 0);
            bKey.Initialize();

            int iOutLength = (saEncrypt.BlockSize >> 3) + 2 + bMessage.Length;
            sedpEncrypted.Body = new byte[iOutLength];
            Array.Copy(bOutput, 0, sedpEncrypted.Body, 0, iOutLength);

            byte[] bESK = esksKeys.GetEncoded();
            byte[] bEncrypted = sedpEncrypted.Generate();

            byte[] bReturn = new byte[bESK.Length + bEncrypted.Length];
            bESK.CopyTo(bReturn, 0);
            bEncrypted.CopyTo(bReturn, bESK.Length);

            return bReturn;
        }
Ejemplo n.º 7
0
        private ESKSequence CreateESKSequence(TransportablePublicKey[] tpkKeys, AsymActions aaAction, SymAlgorithms saAlgo, byte[] bSymKey)
        {
            ESKSequence esksReturn = new ESKSequence();

            for (int i=0; i<tpkKeys.Length; i++) {
                TransportablePublicKey tpkKey = tpkKeys[i];
                PublicKeyPacket pkpKey = tpkKey.FindKey(aaAction);

                if (pkpKey == null)
                    throw new Exception("Could not find subkey fitting to the selected action. Concerned Key: " + tpkKey.PrimaryUserID);

                AsymSessionKeyPacket skpKey = new AsymSessionKeyPacket();
                skpKey.KeyID = pkpKey.KeyID;
                skpKey.PublicAlgorithm = pkpKey.Algorithm;
                skpKey.SymmetricAlgorithm = saAlgo;
                skpKey.SessionKey = bSymKey;

                skpKey.EncryptSessionKey(pkpKey);

                esksReturn.AddAsymSessionKey(skpKey);
            }

            return esksReturn;
        }
Ejemplo n.º 8
0
        public void GenerateKey(string strName, string strEmail, string strKeyType, int iKeySize, long lExpiration, string strPassphrase)
        {
            if (strKeyType == "ElGamal/DSA") {
                System.Security.Cryptography.RandomNumberGenerator rngRand = System.Security.Cryptography.RandomNumberGenerator.Create();

                // let's first create the encryption key
                BigInteger[][] biEncryptionKey = GenerateEncryptionKey(iKeySize);

                // now the signature key
                BigInteger[][] biSignatureKey = GenerateSignatureKey();

                PublicKeyPacket pkpSignatureKey = new PublicKeyPacket(false);
                pkpSignatureKey.Algorithm = AsymAlgorithms.DSA;
                pkpSignatureKey.KeyMaterial = biSignatureKey[0];
                pkpSignatureKey.TimeCreated = DateTime.Now;
                pkpSignatureKey.Version = PublicKeyPacketVersionNumbers.v4;

                SecretKeyPacket skpSignatureKey = new SecretKeyPacket(false);
                skpSignatureKey.SymmetricalAlgorithm = SymAlgorithms.AES256;
                skpSignatureKey.PublicKey = pkpSignatureKey;
                skpSignatureKey.InitialVector = new byte[CipherHelper.CipherBlockSize(SymAlgorithms.AES256)];
                rngRand.GetBytes(skpSignatureKey.InitialVector);
                skpSignatureKey.EncryptKeyMaterial(biSignatureKey[1], strPassphrase);
                skpSignatureKey.PublicKey = pkpSignatureKey;

                PublicKeyPacket pkpEncryptionKey = new PublicKeyPacket(true);
                pkpEncryptionKey.Algorithm = AsymAlgorithms.ElGamal_Encrypt_Only;
                pkpEncryptionKey.KeyMaterial = biEncryptionKey[0];
                pkpEncryptionKey.TimeCreated = DateTime.Now;
                pkpEncryptionKey.Version = PublicKeyPacketVersionNumbers.v4;

                SecretKeyPacket skpEncryptionKey = new SecretKeyPacket(true);
                skpEncryptionKey.SymmetricalAlgorithm = SymAlgorithms.AES256;
                skpEncryptionKey.PublicKey = pkpEncryptionKey;
                skpEncryptionKey.InitialVector = new byte[CipherHelper.CipherBlockSize(SymAlgorithms.AES256)];
                rngRand.GetBytes(skpEncryptionKey.InitialVector);
                skpEncryptionKey.EncryptKeyMaterial(biEncryptionKey[1], strPassphrase);
                skpEncryptionKey.PublicKey = pkpEncryptionKey;

                CertifiedUserID cuiUID = new CertifiedUserID();
                UserIDPacket uipUID = new UserIDPacket();
                uipUID.UserID = strName.Trim() + " <" + strEmail.Trim() + ">";
                cuiUID.UserID = uipUID;
                SignaturePacket spSelfSig = new SignaturePacket();
                spSelfSig.Version = SignaturePacketVersionNumbers.v4;
                spSelfSig.HashAlgorithm = HashAlgorithms.SHA1;
                spSelfSig.KeyID = pkpSignatureKey.KeyID;
                spSelfSig.TimeCreated = DateTime.Now;
                SignatureSubPacket sspPrimaryUserID = new SignatureSubPacket();
                sspPrimaryUserID.Type = SignatureSubPacketTypes.PrimaryUserID;
                sspPrimaryUserID.PrimaryUserID = true;
                spSelfSig.AddSubPacket(sspPrimaryUserID, true);
                SignatureSubPacket sspPreferedSymAlgos = new SignatureSubPacket();
                sspPreferedSymAlgos.Type = SignatureSubPacketTypes.PreferedSymmetricAlgorithms;
                sspPreferedSymAlgos.PreferedSymAlgos = new SymAlgorithms[] {SymAlgorithms.AES256, SymAlgorithms.AES192, SymAlgorithms.AES256, SymAlgorithms.CAST5, SymAlgorithms.Triple_DES};
                spSelfSig.AddSubPacket(sspPreferedSymAlgos, true);
                SignatureSubPacket sspPreferedHashAlgos = new SignatureSubPacket();
                sspPreferedHashAlgos.Type = SignatureSubPacketTypes.PreferedHashAlgorithms;
                sspPreferedHashAlgos.PreferedHashAlgos = new HashAlgorithms[] {HashAlgorithms.SHA1};
                spSelfSig.AddSubPacket(sspPreferedHashAlgos, true);
                if (lExpiration != 0) {
                    SignatureSubPacket sspExpiration = new SignatureSubPacket();
                    sspExpiration.Type = SignatureSubPacketTypes.SignatureExpirationTime;
                    sspExpiration.SignatureExpirationTime = new DateTime(lExpiration);
                    spSelfSig.AddSubPacket(sspExpiration, true);
                }
                cuiUID.Certificates = new System.Collections.ArrayList();
                cuiUID.Sign(spSelfSig, skpSignatureKey, strPassphrase, pkpSignatureKey);

                CertifiedPublicSubkey cpsEncryptionKey = new CertifiedPublicSubkey();
                cpsEncryptionKey.Subkey = pkpEncryptionKey;
                cpsEncryptionKey.SignKeyBindingSignature(pkpSignatureKey, skpSignatureKey, strPassphrase, new DateTime(lExpiration), true);

                TransportablePublicKey tpkPublicKey = new TransportablePublicKey();
                tpkPublicKey.PrimaryKey = pkpSignatureKey;
                tpkPublicKey.SubKeys.Add(cpsEncryptionKey);
                tpkPublicKey.Certifications.Add(cuiUID);

                TransportableSecretKey tskSecretKey = new TransportableSecretKey();
                tskSecretKey.PrimaryKey = skpSignatureKey;
                tskSecretKey.SubKeys.Add(skpEncryptionKey);
                tskSecretKey.UserIDs.Add(uipUID);

                this.pkrKeyRing.AddPublicKey(tpkPublicKey);
                this.skrKeyRing.AddSecretKey(tskSecretKey);
                pkrKeyRing.Save();
                skrKeyRing.Save();

            // it's an RSA key
            } else if (strKeyType == "RSA") {

            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Finds a Key given a keyid. Performs a remote LDAP search if specified.
        /// </summary>
        /// <param name="lKeyID">Key to find</param>
        /// <param name="remote">LDAP search</param>
        /// <returns>a key</returns>
        public TransportablePublicKey Find(ulong lKeyID, bool remote)
        {
            IEnumerator ieKeys = alPublicKeys.GetEnumerator();
            while (ieKeys.MoveNext()) {
                TransportablePublicKey tpkKey = (TransportablePublicKey)ieKeys.Current;
                if (tpkKey.PrimaryKey.KeyID == lKeyID) {
                    return tpkKey;
                }
                IEnumerator ieSubkeys = tpkKey.SubKeys.GetEnumerator();
                while (ieSubkeys.MoveNext()) {
                    CertifiedPublicSubkey cpsSubkey = (CertifiedPublicSubkey)ieSubkeys.Current;
                    if (cpsSubkey.Subkey.KeyID == lKeyID)
                        return tpkKey;
                }
            }

            if (remote) {
                ldapKeyFinder.KeyFinder kf = new ldapKeyFinder.KeyFinder();

                string key = kf.MyLDAPSearch(SharpPrivacyLibrary.LdapKeyServer, SharpPrivacyLibrary.LdapPort,"pgpkey","(pgpsignerid="+lKeyID.ToString("X")+")");
                if (key != null) {
                    ArmorTypes atType = new ArmorTypes();
                    string strKey = Armor.RemoveArmor(key, ref atType, ref key);
                    if (strKey.Length > 0) {
                        TransportablePublicKey tpkKey = new TransportablePublicKey(strKey);
                        AddPublicKey(tpkKey);
                        return tpkKey;
                    }
                }
            }
            return null;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Validates all certificates belonging the the given public key packet
        /// and the current certifications.
        /// </summary>
        /// <remarks>
        /// So far only works with v4 signatures!
        /// </remarks>
        /// <param name="pkpKey">The public key packet to which the userid
        /// belongs.</param>
        /// <param name="pkrRing">A keyring containing all public keys known to
        /// the system. This is neccessary in order to verify the signatures.
        /// </param>
        public void Validate(PublicKeyPacket pkpKey, PublicKeyRing pkrRing)
        {
            IEnumerator ieCertificates = Certificates.GetEnumerator();

            this.validitystatus = ValidityStatus.Valid;
            while (ieCertificates.MoveNext())
            {
                if (ieCertificates.Current is SignaturePacket)
                {
                    SignaturePacket spCert = (SignaturePacket)ieCertificates.Current;

                    TransportablePublicKey tkpSigningKey = pkrRing.Find(spCert.KeyID, true);
                    if (tkpSigningKey == null)
                    {
                        this.validitystatus = ValidityStatus.ValidationKeyUnavailable;
                        continue;
                    }
                    PublicKeyPacket pkpSigningKey = tkpSigningKey.PrimaryKey;

                    if (spCert.Version == SignaturePacketVersionNumbers.v4)
                    {
                        byte[] bKey = new byte[pkpKey.Body.Length + 3];
                        bKey[0] = 0x99;
                        bKey[1] = (byte)((pkpKey.Body.Length >> 8) & 0xFF);
                        bKey[2] = (byte)(pkpKey.Body.Length & 0xFF);
                        Array.Copy(pkpKey.Body, 0, bKey, 3, pkpKey.Body.Length);

                        byte[] bUserID = new byte[UserID.Body.Length + 5];
                        bUserID[0] = 0xb4;
                        bUserID[1] = (byte)((UserID.Body.Length >> 24) & 0xFF);
                        bUserID[2] = (byte)((UserID.Body.Length >> 16) & 0xFF);
                        bUserID[3] = (byte)((UserID.Body.Length >> 8) & 0xFF);
                        bUserID[4] = (byte)(UserID.Body.Length & 0xFF);
                        Array.Copy(UserID.Body, 0, bUserID, 5, UserID.Body.Length);

                        byte[] bData = new byte[bUserID.Length + bKey.Length];
                        Array.Copy(bKey, 0, bData, 0, bKey.Length);
                        Array.Copy(bUserID, 0, bData, bKey.Length, bUserID.Length);

                        spCert.Verify(bData, pkpSigningKey);
                        if (spCert.SignatureStatus == SignatureStatusTypes.Invalid)
                        {
                            this.validitystatus = ValidityStatus.Invalid;
                            continue;
                        }
                        else if (spCert.SignatureStatus == SignatureStatusTypes.Signing_Key_Not_Available)
                        {
                            this.validitystatus = ValidityStatus.ValidationKeyUnavailable;
                            continue;
                        }
                        else if (spCert.SignatureStatus == SignatureStatusTypes.Not_Verified)
                        {
                            this.validitystatus = ValidityStatus.NotYetValidated;
                            continue;
                        }
                    }
                    else
                    {
                        //TODO: Add code for v3 Signature verification
                    }
                }
            }
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Add a key to the keyring
 /// </summary>
 /// <param name="tspk">the key to be added</param>
 public void AddPublicKey(TransportablePublicKey tspk)
 {
     if(tspk != null) {
         if(this.Find(tspk.PrimaryKey.KeyID, false) == null) {
             this.Add(tspk);
         }
     }
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Verifies key signatures
        /// </summary>
        /// <param name="tpkKey">the key to be verified</param>
        /// <returns>
        /// list of invalid signatures or objects containing invalid signatures:
        /// SignaturePacket
        /// CertifiedUserID
        /// CertifiedPublicSubkey
        /// </returns>
        private ArrayList verifySignatures(TransportablePublicKey tpkKey)
        {
            ArrayList signaturesNotOK = new ArrayList();

            //Verify Revocation Signatures
            foreach(SignaturePacket revocation in tpkKey.RevocationSignatures) {
                if(revocation.KeyID == tpkKey.PrimaryKey.KeyID) {
                    PublicKeyPacket pkpKey = tpkKey.FindKey(revocation.KeyID);
                    byte[] key = new byte[tpkKey.PrimaryKey.Length];
                    tpkKey.PrimaryKey.Header.CopyTo(key,0);
                    tpkKey.PrimaryKey.Body.CopyTo(key,tpkKey.PrimaryKey.Header.Length);
                    if(pkpKey == null) {
                        revocation.SignatureStatus = SignatureStatusTypes.Signing_Key_Not_Available;
                        signaturesNotOK.Add(revocation);
                    } else {
                        revocation.Verify(key,pkpKey);
                        if(revocation.SignatureStatus == SignatureStatusTypes.Invalid ||
                            revocation.SignatureStatus == SignatureStatusTypes.Not_Verified ||
                            revocation.SignatureStatus == SignatureStatusTypes.Signing_Key_Not_Available)
                        {
                            signaturesNotOK.Add(revocation);
                        }
                    }
                } else {
                    TransportablePublicKey revtpkKey = this.Find(revocation.KeyID, true);
                    if (revtpkKey != null) {
                        foreach (SignaturePacket spPacket in tpkKey.RevocationKeys) {
                            foreach (BigInteger revoker in spPacket.FindRevokerKeys()) {
                                if(revoker.ToString() == revtpkKey.PrimaryKey.Fingerprint.ToString()) {
                                    PublicKeyPacket pkpKey = revtpkKey.PrimaryKey;
                                    byte[] key = new byte[tpkKey.PrimaryKey.Length];
                                    tpkKey.PrimaryKey.Header.CopyTo(key,0);
                                    tpkKey.PrimaryKey.Body.CopyTo(key,tpkKey.PrimaryKey.Header.Length);
                                    revocation.Verify(key,pkpKey);
                                    if(revocation.SignatureStatus == SignatureStatusTypes.Invalid ||
                                        revocation.SignatureStatus == SignatureStatusTypes.Not_Verified ||
                                        revocation.SignatureStatus == SignatureStatusTypes.Signing_Key_Not_Available)
                                    {
                                        signaturesNotOK.Add(revocation);
                                    }
                                }
                            }
                        }
                    } else {
                        revocation.SignatureStatus = SignatureStatusTypes.Signing_Key_Not_Available;
                        signaturesNotOK.Add(revocation);
                    }
                }
            }

            //Verify UserID
            foreach(CertifiedUserID userId in tpkKey.Certifications) {
                userId.Validate(tpkKey.PrimaryKey,this);
                if(userId.CertificationValidityStatus == CertifiedUserID.ValidityStatus.Invalid ||
                    userId.CertificationValidityStatus == CertifiedUserID.ValidityStatus.NotYetValidated ||
                    userId.CertificationValidityStatus == CertifiedUserID.ValidityStatus.ValidationKeyUnavailable)
                {
                    foreach(SignaturePacket sp in userId.Certificates) {
                        if(sp.SignatureStatus != SignatureStatusTypes.Valid)
                            signaturesNotOK.Add(sp);
                    }
                }
            }

            foreach(CertifiedPublicSubkey cps in tpkKey.SubKeys) {
                if(cps.KeyBindingSignature == null) {
                    signaturesNotOK.Add(cps);
                } else {
                    cps.VerifyKeyBindingSignature(tpkKey.PrimaryKey);
                    if(cps.KeyBindingSignature.SignatureStatus == SignatureStatusTypes.Invalid ||
                        cps.KeyBindingSignature.SignatureStatus == SignatureStatusTypes.Not_Verified ||
                        cps.KeyBindingSignature.SignatureStatus == SignatureStatusTypes.Signing_Key_Not_Available)
                    {
                        signaturesNotOK.Add(cps.KeyBindingSignature);
                    }
                }

                //Verify Subkey Revocation Signature
                SignaturePacket revocation = cps.RevocationSignature;
                if(revocation != null) {
                    if(revocation.KeyID == tpkKey.PrimaryKey.KeyID) {
                        byte[] subkey = new byte[cps.Subkey.Length];
                        cps.Subkey.Header.CopyTo(subkey,0);
                        cps.Subkey.Body.CopyTo(subkey,cps.Subkey.Header.Length);
                        subkey[0]=0x99;

                        byte[] mainkey = new byte[tpkKey.PrimaryKey.Length];
                        tpkKey.PrimaryKey.Header.CopyTo(mainkey,0);
                        tpkKey.PrimaryKey.Body.CopyTo(mainkey,tpkKey.PrimaryKey.Header.Length);

                        byte[] key = new byte[subkey.Length+mainkey.Length];
                        mainkey.CopyTo(key,0);
                        subkey.CopyTo(key,mainkey.Length);

                        revocation.Verify(key,tpkKey.PrimaryKey);
                        if(revocation.SignatureStatus == SignatureStatusTypes.Invalid ||
                            revocation.SignatureStatus == SignatureStatusTypes.Not_Verified ||
                            revocation.SignatureStatus == SignatureStatusTypes.Signing_Key_Not_Available)
                        {
                            signaturesNotOK.Add(revocation);
                        }

                    } else {
                        TransportablePublicKey revtpkKey = this.Find(revocation.KeyID, true);
                        if(revtpkKey != null) {
                            foreach(SignaturePacket spPacket in tpkKey.RevocationKeys) {
                                foreach(BigInteger revoker in spPacket.FindRevokerKeys()) {
                                    if(revoker.ToString() == revtpkKey.PrimaryKey.Fingerprint.ToString()) {
                                        byte[] subkey = new byte[cps.Subkey.Length];
                                        cps.Subkey.Header.CopyTo(subkey,0);
                                        cps.Subkey.Body.CopyTo(subkey,cps.Subkey.Header.Length);
                                        subkey[0]=0x99;

                                        byte[] mainkey = new byte[revtpkKey.PrimaryKey.Length];
                                        tpkKey.PrimaryKey.Header.CopyTo(mainkey,0);
                                        tpkKey.PrimaryKey.Body.CopyTo(mainkey,revtpkKey.PrimaryKey.Header.Length);

                                        byte[] key = new byte[subkey.Length+mainkey.Length];
                                        mainkey.CopyTo(key,0);
                                        subkey.CopyTo(key,mainkey.Length);

                                        revocation.Verify(key,revtpkKey.PrimaryKey);
                                        if(revocation.SignatureStatus == SignatureStatusTypes.Invalid ||
                                            revocation.SignatureStatus == SignatureStatusTypes.Not_Verified ||
                                            revocation.SignatureStatus == SignatureStatusTypes.Signing_Key_Not_Available)
                                        {
                                            signaturesNotOK.Add(revocation);
                                        }
                                    }
                                }
                            }
                        } else {
                            signaturesNotOK.Add(revocation);
                        }
                    }
                }
            }
            return signaturesNotOK;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Private method to add a key doing checks
        /// </summary>
        /// <param name="tpkKey">the key to be saved</param>
        private void Add(TransportablePublicKey tpkKey)
        {
            bIsUpdated = true;
            TransportablePublicKey local = null;
            if ((local = this.Find(tpkKey.PrimaryKey.KeyID, false)) == null) {
                alPublicKeys.Add(tpkKey);
            } else {
                TransportablePublicKey joinKey = new TransportablePublicKey();
                joinKey.PrimaryKey = local.PrimaryKey;
                //Revocations
                ArrayList toBeAdded = new ArrayList();
                toBeAdded.AddRange(local.RevocationSignatures);
                toBeAdded.AddRange(tpkKey.RevocationSignatures);
                foreach(SignaturePacket localpacket in local.RevocationSignatures) {
                    foreach(SignaturePacket packet in tpkKey.RevocationSignatures) {
                        if(localpacket.Body == packet.Body && localpacket.Header == packet.Header) {
                            toBeAdded.Remove(packet);
                            continue;
                        }
                    }
                }
                joinKey.RevocationSignatures=toBeAdded;

                //Revokers
                toBeAdded = new ArrayList();
                toBeAdded.AddRange(local.RevocationKeys);
                toBeAdded.AddRange(tpkKey.RevocationKeys);
                foreach(SignaturePacket localpacket in local.RevocationKeys) {
                    foreach(SignaturePacket packet in tpkKey.RevocationKeys) {
                        if(localpacket.Body == packet.Body && localpacket.Header == packet.Header) {
                            toBeAdded.Remove(packet);
                            continue;
                        }
                    }
                }
                joinKey.RevocationKeys=toBeAdded;

                //CERTIFICATES
                toBeAdded = new ArrayList();
                toBeAdded.AddRange(local.Certifications);
                toBeAdded.AddRange(tpkKey.Certifications);
                foreach(CertifiedUserID localpacket in local.Certifications) {
                    foreach(CertifiedUserID packet in tpkKey.Certifications) {
                        if(localpacket.UserID == packet.UserID) {
                            ArrayList certificatesToBeAdded = new ArrayList();
                            certificatesToBeAdded.AddRange(localpacket.Certificates);
                            certificatesToBeAdded.AddRange(packet.Certificates);
                            foreach(SignaturePacket signatureLocal in localpacket.Certificates) {
                                foreach(SignaturePacket signature in localpacket.Certificates) {
                                    if(signatureLocal.Header == signature.Header && signatureLocal.Body == signature.Body) {
                                        certificatesToBeAdded.Remove(signature);
                                        continue;
                                    }
                                }
                            }
                            localpacket.Certificates = certificatesToBeAdded;
                            toBeAdded.Remove(packet);
                            continue;
                        }
                    }
                }
                joinKey.Certifications = toBeAdded;

                //SUBKEYS
                toBeAdded = new ArrayList();
                toBeAdded.AddRange(local.SubKeys);
                toBeAdded.AddRange(tpkKey.SubKeys);
                foreach(CertifiedPublicSubkey localpacket in local.SubKeys) {
                    foreach(CertifiedPublicSubkey packet in tpkKey.SubKeys) {
                        if(localpacket.Subkey.KeyID == packet.Subkey.KeyID) {
                            toBeAdded.Remove(packet);
                            if(localpacket.KeyBindingSignature == null)
                                localpacket.KeyBindingSignature = packet.KeyBindingSignature;
                            if(localpacket.RevocationSignature == null)
                                localpacket.RevocationSignature = packet.RevocationSignature;
                            continue;
                        }
                    }
                }
                joinKey.SubKeys=toBeAdded;

                alPublicKeys.Remove(local);
                alPublicKeys.Add(joinKey);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Finds a local or remote key given its fingerprint
        /// </summary>
        /// <param name="fingerprint">fingerprint</param>
        /// <returns>a public key</returns>
        public TransportablePublicKey FindPublicKey(string fingerprint)
        {
            IEnumerator ieKeys = this.PublicKeys.GetEnumerator();
            while (ieKeys.MoveNext()) {
                if (!(ieKeys.Current is TransportablePublicKey)) {
                    continue;
                }
                TransportablePublicKey key = ((TransportablePublicKey)ieKeys.Current);
                if(key.PrimaryKey.Fingerprint.ToString() == fingerprint) {
                    return key;
                }
            }

            ldapKeyFinder.KeyFinder kf = new ldapKeyFinder.KeyFinder();
            string remoteKey = kf.MyLDAPSearch(SharpPrivacyLibrary.LdapKeyServer,SharpPrivacyLibrary.LdapPort,"pgpkey","(pgpsignerid="+fingerprint+")");
            if (remoteKey != null) {
                ArmorTypes atType = new ArmorTypes();
                string strKey = Armor.RemoveArmor(remoteKey, ref atType, ref remoteKey);
                if (strKey.Length > 0) {
                    TransportablePublicKey tpkKey = new TransportablePublicKey(strKey);
                    AddPublicKey(tpkKey);
                    return tpkKey;
                }
            }

            return null;
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Signs a key 
        /// </summary>
        /// <param name="tspKey">key to be signed</param>
        /// <param name="cuidTobeSigned">user id to be signed</param>
        /// <param name="skpKeySigner">signer private key</param>
        /// <param name="strPassphrase">signer passphrase</param>
        /// <param name="exportable">exportable signature</param>
        /// <param name="expirationTime">expiration time (new DateTime(0) == never)</param>
        /// <param name="isRevocable"></param>
        public void SignKey(TransportablePublicKey tspKey, CertifiedUserID cuidTobeSigned, TransportableSecretKey skpKeySigner, string strPassphrase, bool exportable, DateTime expirationTime, bool isRevocable)
        {
            SignaturePacket spSig = new SignaturePacket();
            spSig.Version = SignaturePacketVersionNumbers.v4;
            spSig.HashAlgorithm = HashAlgorithms.SHA1;
            spSig.KeyID = skpKeySigner.PrimaryKey.PublicKey.KeyID;
            spSig.TimeCreated = DateTime.Now;
            SignatureSubPacket sspExportableSignature = new SignatureSubPacket();
            sspExportableSignature.Type = SignatureSubPacketTypes.ExportableSignature;
            sspExportableSignature.ExportableSignature = exportable;
            spSig.AddSubPacket(sspExportableSignature, false);
            if (!isRevocable) {
                SignatureSubPacket sspRevocable = new SignatureSubPacket();
                sspRevocable.Type = SignatureSubPacketTypes.Revocable;
                sspRevocable.Revocable = isRevocable;
                spSig.AddSubPacket(sspRevocable, true);
            }
            if (expirationTime.Ticks != 0) {
                SignatureSubPacket sspExpiration = new SignatureSubPacket();
                sspExpiration.Type = SignatureSubPacketTypes.KeyExpirationTime;
                sspExpiration.KeyExpirationTime = new DateTime(expirationTime.Ticks + (new DateTime(1970,1,2)).Ticks - tspKey.PrimaryKey.TimeCreated.Ticks);
                spSig.AddSubPacket(sspExpiration, true);
            }

            cuidTobeSigned.Sign(spSig, skpKeySigner.PrimaryKey, strPassphrase, tspKey.PrimaryKey);
        }
Ejemplo n.º 16
0
        public void EncryptFile(string strPath, string strOutput, ulong[] lTargetKeyIDs)
        {
            TransportablePublicKey[] tpkSelectedKeys = new TransportablePublicKey[lTargetKeyIDs.Length];
            for (int i=0; i<lTargetKeyIDs.Length; i++)
                tpkSelectedKeys[i] = pkrKeyRing.Find(lTargetKeyIDs[i], true);

            System.IO.FileStream fsFile = new FileStream(strPath, FileMode.Open);
            BinaryReader brReader = new BinaryReader(fsFile);
            byte[] bFileContent = brReader.ReadBytes((int)fsFile.Length);
            brReader.Close();
            fsFile.Close();

            LiteralMessage lmMessage = new LiteralMessage(DataFormatTypes.Binary);
            lmMessage.Binary = bFileContent;
            lmMessage.TimeCreated = DateTime.Now;
            int iLastBackslash = strPath.LastIndexOf("\\");
            lmMessage.Filename = strPath.Substring(iLastBackslash + 1, strPath.Length - iLastBackslash - 1);

            byte[] bReturn = EncryptMessage(lmMessage, lTargetKeyIDs);

            FileStream fsOut = new FileStream(strOutput, FileMode.CreateNew);
            BinaryWriter bwWrite = new BinaryWriter(fsOut);

            bwWrite.Write(bReturn);
            bwWrite.Close();
            fsOut.Close();
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Generate a key pair
        /// </summary>
        /// <param name="iKeySize">Encription key size</param>
        /// <param name="strPassphrase">passhrase for the key pair</param>
        /// <param name="userID">primary user id</param>
        /// <param name="email">user email</param>
        /// <param name="notation">xml encoded user info</param>
        /// <param name="expirationTime">expiration date of the primary key (new DateTime(0) == never)</param>
        /// <param name="keyType">1: RSA/DSA   0:Elgamal/DSA(DEFAULT)</param>
        /// <param name="isRevocableKey">revocable?</param>
        /// <param name="isRevocableSubkey">revocable subkey?</param>
        public void GenerateKey(int iKeySize, string strPassphrase, string userID, string email, string notation, DateTime expirationTime, int keyType, bool isRevocableKey, bool isRevocableSubkey)
        {
            if(iKeySize % 1024 != 0)
                throw new Exception("Keysize must be a 1024 multiple");

            System.Security.Cryptography.RandomNumberGenerator rngRand;

            // let's first create the encryption key
            BigInteger[][] biEncryptionKey;
            if (keyType == 1) {
                // it's a RSA/DSA key
                biEncryptionKey = GenerateRSAEncryptionKey(iKeySize);
            } else {
                // it's an elgamal/DSA key DEFAULF
                biEncryptionKey = GenerateElGamalEncryptionKey(iKeySize);
            }

            // now the signature key
            BigInteger[][] biSignatureKey = GenerateDSASignatureKey();

            PublicKeyPacket pkpSignatureKey = new PublicKeyPacket(false);
            pkpSignatureKey.Algorithm = AsymAlgorithms.DSA;
            pkpSignatureKey.KeyMaterial = biSignatureKey[0];
            pkpSignatureKey.TimeCreated = DateTime.Now;
            pkpSignatureKey.Version = PublicKeyPacketVersionNumbers.v4;

            SecretKeyPacket skpSignatureKey = new SecretKeyPacket(false);
            skpSignatureKey.SymmetricalAlgorithm = SymAlgorithms.AES256;
            skpSignatureKey.PublicKey = pkpSignatureKey;
            skpSignatureKey.InitialVector = new byte[CipherHelper.CipherBlockSize(SymAlgorithms.AES256)];
            rngRand = System.Security.Cryptography.RandomNumberGenerator.Create();
            rngRand.GetBytes(skpSignatureKey.InitialVector);
            skpSignatureKey.EncryptKeyMaterial(biSignatureKey[1], strPassphrase);
            skpSignatureKey.PublicKey = pkpSignatureKey;

            PublicKeyPacket pkpEncryptionKey = new PublicKeyPacket(true);
            if (keyType == 0) {
                // it's an elgamal/DSA key
                pkpEncryptionKey.Algorithm = AsymAlgorithms.ElGamal_Encrypt_Only;
            } else if (keyType == 1) {
                // it's a RSA/DSA key
                pkpEncryptionKey.Algorithm = AsymAlgorithms.RSA_Encrypt_Only;
            }
            pkpEncryptionKey.KeyMaterial = biEncryptionKey[0];
            pkpEncryptionKey.TimeCreated = DateTime.Now;
            pkpEncryptionKey.Version = PublicKeyPacketVersionNumbers.v4;

            SecretKeyPacket skpEncryptionKey = new SecretKeyPacket(true);
            skpEncryptionKey.SymmetricalAlgorithm = SymAlgorithms.AES256;
            skpEncryptionKey.PublicKey = pkpEncryptionKey;
            skpEncryptionKey.InitialVector = new byte[CipherHelper.CipherBlockSize(SymAlgorithms.AES256)];
            rngRand = System.Security.Cryptography.RandomNumberGenerator.Create();
            rngRand.GetBytes(skpEncryptionKey.InitialVector);
            skpEncryptionKey.EncryptKeyMaterial(biEncryptionKey[1], strPassphrase);
            skpEncryptionKey.PublicKey = pkpEncryptionKey;

            CertifiedUserID cuiUID = new CertifiedUserID();
            UserIDPacket uipUID = new UserIDPacket();
            uipUID.UserID = userID.Trim() + " <" + email.Trim() + ">";
            cuiUID.UserID = uipUID;
            SignaturePacket spSelfSig = new SignaturePacket();
            if (notation != null) {
                SignatureSubPacket sspNotation = new SignatureSubPacket();
                sspNotation.Type = SignatureSubPacketTypes.NotationData;
                sspNotation.NotationName = "PersonalData";
                sspNotation.NotationValue = notation;
                spSelfSig.AddSubPacket(sspNotation,false);
            }
            if (expirationTime.Ticks != 0) {
                SignatureSubPacket sspExpiration = new SignatureSubPacket();
                sspExpiration.Type = SignatureSubPacketTypes.KeyExpirationTime;
                sspExpiration.KeyExpirationTime = new DateTime(expirationTime.Ticks + (new DateTime(1970,1,2)).Ticks - pkpEncryptionKey.TimeCreated.Ticks);
                spSelfSig.AddSubPacket(sspExpiration, true);
            }
            if (!isRevocableKey) {
                SignatureSubPacket sspRevocable = new SignatureSubPacket();
                sspRevocable.Type = SignatureSubPacketTypes.Revocable;
                sspRevocable.Revocable = isRevocableKey;
                spSelfSig.AddSubPacket(sspRevocable, true);
            }
            SignatureSubPacket sspPrimaryUID = new SignatureSubPacket();
            sspPrimaryUID.Type = SignatureSubPacketTypes.PrimaryUserID;
            sspPrimaryUID.Revocable = true;
            spSelfSig.AddSubPacket(sspPrimaryUID, true);

            spSelfSig.Version = SignaturePacketVersionNumbers.v4;
            spSelfSig.HashAlgorithm = HashAlgorithms.SHA1;
            spSelfSig.KeyID = pkpSignatureKey.KeyID;
            spSelfSig.TimeCreated = DateTime.Now;
            SignatureSubPacket sspPrimaryUserID = new SignatureSubPacket();
            sspPrimaryUserID.Type = SignatureSubPacketTypes.PrimaryUserID;
            sspPrimaryUserID.PrimaryUserID = true;
            spSelfSig.AddSubPacket(sspPrimaryUserID, true);
            SignatureSubPacket sspPreferedSymAlgos = new SignatureSubPacket();
            sspPreferedSymAlgos.Type = SignatureSubPacketTypes.PreferedSymmetricAlgorithms;
            sspPreferedSymAlgos.PreferedSymAlgos = new SymAlgorithms[] {SymAlgorithms.AES256, SymAlgorithms.AES192, SymAlgorithms.AES256, SymAlgorithms.CAST5, SymAlgorithms.Triple_DES};
            spSelfSig.AddSubPacket(sspPreferedSymAlgos, true);
            SignatureSubPacket sspPreferedHashAlgos = new SignatureSubPacket();
            sspPreferedHashAlgos.Type = SignatureSubPacketTypes.PreferedHashAlgorithms;
            sspPreferedHashAlgos.PreferedHashAlgos = new HashAlgorithms[] {HashAlgorithms.SHA1};
            spSelfSig.AddSubPacket(sspPreferedHashAlgos, true);

            cuiUID.Certificates = new System.Collections.ArrayList();
            cuiUID.Sign(spSelfSig, skpSignatureKey, strPassphrase, pkpSignatureKey);

            CertifiedPublicSubkey cpsEncryptionKey = new CertifiedPublicSubkey();
            cpsEncryptionKey.Subkey = pkpEncryptionKey;
            cpsEncryptionKey.SignKeyBindingSignature(pkpSignatureKey, skpSignatureKey, strPassphrase, expirationTime, isRevocableSubkey);

            TransportablePublicKey tpkPublicKey = new TransportablePublicKey();
            tpkPublicKey.PrimaryKey = pkpSignatureKey;
            tpkPublicKey.SubKeys.Add(cpsEncryptionKey);
            tpkPublicKey.Certifications.Add(cuiUID);

            this.PublicRing.AddPublicKey(tpkPublicKey);

            TransportableSecretKey tskSecretKey = new TransportableSecretKey();
            tskSecretKey.PrimaryKey = skpSignatureKey;
            tskSecretKey.SubKeys.Add(skpEncryptionKey);
            tskSecretKey.UserIDs.Add(uipUID);

            this.SecretRing.AddSecretKey(tskSecretKey);
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Removes a key from the ring
 /// </summary>
 /// <param name="tpkKey">the key to remove</param>
 public void Delete(TransportablePublicKey tpkKey)
 {
     bIsUpdated = true;
     alPublicKeys.Remove(tpkKey);
 }