コード例 #1
0
 public DsaPublicBcpgKey(BcpgInputStream bcpgIn)
 {
     p = new MPInteger(bcpgIn);
     q = new MPInteger(bcpgIn);
     g = new MPInteger(bcpgIn);
     y = new MPInteger(bcpgIn);
 }
コード例 #2
0
 public DsaPublicBcpgKey(BigInteger p, BigInteger q, BigInteger g, BigInteger y)
 {
     this.p = new MPInteger(p);
     this.q = new MPInteger(q);
     this.g = new MPInteger(g);
     this.y = new MPInteger(y);
 }
コード例 #3
0
    public override void Encode(BcpgOutputStream bcpgOut)
    {
        byte[] encoded = oid.GetEncoded();
        bcpgOut.Write(encoded, 1, encoded.Length - 1);
        MPInteger bcpgObject = new MPInteger(point);

        bcpgOut.WriteObject(bcpgObject);
    }
コード例 #4
0
 public RsaSecretBcpgKey(BcpgInputStream bcpgIn)
 {
     d    = new MPInteger(bcpgIn);
     p    = new MPInteger(bcpgIn);
     q    = new MPInteger(bcpgIn);
     u    = new MPInteger(bcpgIn);
     expP = d.Value.Remainder(p.Value.Subtract(BigInteger.One));
     expQ = d.Value.Remainder(q.Value.Subtract(BigInteger.One));
     crt  = q.Value.ModInverse(p.Value);
 }
コード例 #5
0
        public byte[] CalculateFingerprint(PublicKeyPacket publicPk)
        {
            IBcpgKey key = publicPk.Key;

            if (publicPk.Version <= 3)
            {
                RsaPublicBcpgKey rK = (RsaPublicBcpgKey)key;

                try
                {
                    // TODO: MD5 needs to go in the main API...
                    MD5Digest digest = new MD5Digest();

                    byte[] bytes = new MPInteger(rK.Modulus).GetEncoded();
                    digest.BlockUpdate(bytes, 2, bytes.Length - 2);

                    bytes = new MPInteger(rK.PublicExponent).GetEncoded();
                    digest.BlockUpdate(bytes, 2, bytes.Length - 2);

                    byte[] digBuf = new byte[digest.GetDigestSize()];

                    digest.DoFinal(digBuf, 0);

                    return(digBuf);
                }
                catch (IOException e)
                {
                    throw new PgpException("can't encode key components: " + e.Message, e);
                }
            }
            else
            {
                try
                {
                    byte[] kBytes = publicPk.GetEncodedContents();

                    IStreamCalculator <IBlockResult> hashCalc = CryptoServicesRegistrar.CreateService(FipsShs.Sha1).CreateCalculator();
                    Stream hStream = hashCalc.Stream;

                    hStream.WriteByte((byte)0x99);
                    hStream.WriteByte((byte)(kBytes.Length >> 8));
                    hStream.WriteByte((byte)kBytes.Length);
                    hStream.Write(kBytes, 0, kBytes.Length);

                    hStream.Close();

                    return(hashCalc.GetResult().Collect());
                }
                catch (IOException e)
                {
                    throw new PgpException("can't encode key components: " + e.Message, e);
                }
            }
        }
コード例 #6
0
            private byte[] EncryptSessionInfo(byte[] sessionInfo, SecureRandom random)
            {
                if (pubKey.Algorithm != PublicKeyAlgorithmTag.EC)
                {
                    IBufferedCipher cipher;
                    switch (pubKey.Algorithm)
                    {
                    case PublicKeyAlgorithmTag.RsaGeneral:
                    case PublicKeyAlgorithmTag.RsaEncrypt:
                        cipher = CipherUtilities.GetCipher("RSA//PKCS1Padding");
                        break;

                    case PublicKeyAlgorithmTag.ElGamalEncrypt:
                    case PublicKeyAlgorithmTag.ElGamalGeneral:
                        cipher = CipherUtilities.GetCipher("ElGamal/ECB/PKCS1Padding");
                        break;

                    case PublicKeyAlgorithmTag.Dsa:
                        throw new PgpException("Can't use DSA for encryption.");

                    case PublicKeyAlgorithmTag.ECDsa:
                        throw new PgpException("Can't use ECDSA for encryption.");

                    default:
                        throw new PgpException(string.Concat((object)"unknown asymmetric algorithm: ", (object)pubKey.Algorithm));
                    }
                    AsymmetricKeyParameter parameters = pubKey.GetKey();
                    cipher.Init(forEncryption: true, new ParametersWithRandom(parameters, random));
                    return(cipher.DoFinal(sessionInfo));
                }
                ECDHPublicBcpgKey eCDHPublicBcpgKey = (ECDHPublicBcpgKey)pubKey.PublicKeyPacket.Key;
                IAsymmetricCipherKeyPairGenerator keyPairGenerator = GeneratorUtilities.GetKeyPairGenerator("ECDH");

                keyPairGenerator.Init(new ECKeyGenerationParameters(eCDHPublicBcpgKey.CurveOid, random));
                AsymmetricCipherKeyPair asymmetricCipherKeyPair = keyPairGenerator.GenerateKeyPair();
                ECPrivateKeyParameters  eCPrivateKeyParameters  = (ECPrivateKeyParameters)asymmetricCipherKeyPair.Private;
                ECPublicKeyParameters   eCPublicKeyParameters   = (ECPublicKeyParameters)asymmetricCipherKeyPair.Public;
                ECPublicKeyParameters   eCPublicKeyParameters2  = (ECPublicKeyParameters)pubKey.GetKey();
                ECPoint      s           = eCPublicKeyParameters2.Q.Multiply(eCPrivateKeyParameters.D).Normalize();
                KeyParameter parameters2 = new KeyParameter(Rfc6637Utilities.CreateKey(pubKey.PublicKeyPacket, s));
                IWrapper     wrapper     = PgpUtilities.CreateWrapper(eCDHPublicBcpgKey.SymmetricKeyAlgorithm);

                wrapper.Init(forWrapping: true, new ParametersWithRandom(parameters2, random));
                byte[] array   = PgpPad.PadSessionData(sessionInfo);
                byte[] array2  = wrapper.Wrap(array, 0, array.Length);
                byte[] encoded = new MPInteger(new BigInteger(1, eCPublicKeyParameters.Q.GetEncoded(compressed: false))).GetEncoded();
                byte[] array3  = new byte[encoded.Length + 1 + array2.Length];
                global::System.Array.Copy((global::System.Array)encoded, 0, (global::System.Array)array3, 0, encoded.Length);
                array3[encoded.Length] = (byte)array2.Length;
                global::System.Array.Copy((global::System.Array)array2, 0, (global::System.Array)array3, encoded.Length + 1, array2.Length);
                return(array3);
            }
コード例 #7
0
    internal PublicKeyEncSessionPacket(BcpgInputStream bcpgIn)
    {
        version   = bcpgIn.ReadByte();
        keyId    |= (long)bcpgIn.ReadByte() << 56;
        keyId    |= (long)bcpgIn.ReadByte() << 48;
        keyId    |= (long)bcpgIn.ReadByte() << 40;
        keyId    |= (long)bcpgIn.ReadByte() << 32;
        keyId    |= (long)bcpgIn.ReadByte() << 24;
        keyId    |= (long)bcpgIn.ReadByte() << 16;
        keyId    |= (long)bcpgIn.ReadByte() << 8;
        keyId    |= (uint)bcpgIn.ReadByte();
        algorithm = (PublicKeyAlgorithmTag)bcpgIn.ReadByte();
        switch (algorithm)
        {
        case PublicKeyAlgorithmTag.RsaGeneral:
        case PublicKeyAlgorithmTag.RsaEncrypt:
            data = new byte[1][]
            {
                new MPInteger(bcpgIn).GetEncoded()
            };
            break;

        case PublicKeyAlgorithmTag.ElGamalEncrypt:
        case PublicKeyAlgorithmTag.ElGamalGeneral:
        {
            MPInteger mPInteger  = new MPInteger(bcpgIn);
            MPInteger mPInteger2 = new MPInteger(bcpgIn);
            data = new byte[2][]
            {
                mPInteger.GetEncoded(),
                    mPInteger2.GetEncoded()
            };
            break;
        }

        case PublicKeyAlgorithmTag.EC:
            data = new byte[1][]
            {
                Streams.ReadAll(bcpgIn)
            };
            break;

        default:
            throw new IOException("unknown PGP public key algorithm encountered");
        }
    }
コード例 #8
0
ファイル: Program.cs プロジェクト: jvinkovic/SSH-simulator
        private static void test()
        {
            var msg       = "Ivona je mala!";
            var msg_array = Encoding.ASCII.GetBytes(msg);
            var key       = makeKey();
            var iv        = makeIV();
            var cry       = Encrypt3DES_CBC(msg_array, key, iv, true);
            var decrx     = Encrypt3DES_CBC(cry, key, iv, false);
            var izlaz     = Encoding.ASCII.GetString(decrx);

            StreamReader txtStream = File.OpenText(@"ServerCert\server_rsa.pem");
            PemReader    reader    = new PemReader(txtStream);
            var          obj       = reader.ReadPemObject();
            var          tst       = obj.Generate();
            var          t2        = Convert.ToBase64String((obj.Content));

            var num       = new BigInteger("789");
            var publicKey = new MPInteger(num);

            var pubStringKey = publicKey.Value.ToString();
            int pubLength    = pubStringKey.Length;

            var size = BitConverter.GetBytes(pubLength);

            // reverse zbog toga da ide iz little u big endian - ("normalni")
            Array.Reverse(size);

            List <byte> rezultat = new List <byte>();

            rezultat.AddRange(size);
            rezultat.AddRange(Encoding.ASCII.GetBytes(pubStringKey));

            var all = rezultat.ToArray();

            byte[] velicina = new byte[4];
            all.Take(size.Length);
            Array.Reverse(velicina);
            int packetSize = BitConverter.ToInt32(velicina, 0);

            var broj       = all.Skip(4).ToArray();
            var brojString = Encoding.ASCII.GetString(broj);
            var bigintBroj = new BigInteger(brojString);

            bool valja = bigintBroj.Equals(num);
        }
コード例 #9
0
    public RsaSecretBcpgKey(BigInteger d, BigInteger p, BigInteger q)
    {
        int num = p.CompareTo(q);

        if (num >= 0)
        {
            if (num == 0)
            {
                throw new ArgumentException("p and q cannot be equal");
            }
            BigInteger bigInteger = p;
            p = q;
            q = bigInteger;
        }
        this.d = new MPInteger(d);
        this.p = new MPInteger(p);
        this.q = new MPInteger(q);
        u      = new MPInteger(p.ModInverse(q));
        expP   = d.Remainder(p.Subtract(BigInteger.One));
        expQ   = d.Remainder(q.Subtract(BigInteger.One));
        crt    = q.ModInverse(p);
    }
コード例 #10
0
        /// <summary>Return a V3 signature object containing the current signature state.</summary>
        public PgpSignature Generate()
        {
            long creationTime = DateTimeUtilities.CurrentUnixMs() / 1000L;

            byte[] hData = new byte[]
            {
                (byte)signatureType,
                (byte)(creationTime >> 24),
                (byte)(creationTime >> 16),
                (byte)(creationTime >> 8),
                (byte)creationTime
            };

            sig.BlockUpdate(hData, 0, hData.Length);
            dig.BlockUpdate(hData, 0, hData.Length);

            byte[] sigBytes    = sig.GenerateSignature();
            byte[] digest      = DigestUtilities.DoFinal(dig);
            byte[] fingerPrint = new byte[] { digest[0], digest[1] };

            MPInteger[] sigValues;
            if (keyAlgorithm == PublicKeyAlgorithmTag.RsaSign ||
                keyAlgorithm == PublicKeyAlgorithmTag.RsaGeneral)
            // an RSA signature
            {
                sigValues = new MPInteger[] { new MPInteger(new BigInteger(1, sigBytes)) };
            }
            else
            {
                sigValues = PgpUtilities.DsaSigToMpi(sigBytes);
            }

            return(new PgpSignature(
                       new SignaturePacket(3, signatureType, privKey.KeyId, keyAlgorithm,
                                           hashAlgorithm, creationTime * 1000L, fingerPrint, sigValues)));
        }
コード例 #11
0
        /// <summary>Return a V3 signature object containing the current signature state.</summary>
        public PgpSignature Generate()
        {
            long creationTime = DateTimeUtilities.CurrentUnixMs() / 1000L;

            byte[] hData = new byte[]
            {
                (byte) signatureType,
                (byte)(creationTime >> 24),
                (byte)(creationTime >> 16),
                (byte)(creationTime >> 8),
                (byte) creationTime
            };

            sig.BlockUpdate(hData, 0, hData.Length);
            dig.BlockUpdate(hData, 0, hData.Length);

            byte[] sigBytes = sig.GenerateSignature();
            byte[] digest = DigestUtilities.DoFinal(dig);
            byte[] fingerPrint = new byte[]{ digest[0], digest[1] };

            MPInteger[] sigValues;
            if (keyAlgorithm == PublicKeyAlgorithmTag.RsaSign
                || keyAlgorithm == PublicKeyAlgorithmTag.RsaGeneral)
                // an RSA signature
            {
                sigValues = new MPInteger[]{ new MPInteger(new BigInteger(1, sigBytes)) };
            }
            else
            {
                sigValues = PgpUtilities.DsaSigToMpi(sigBytes);
            }

            return new PgpSignature(
                new SignaturePacket(3, signatureType, privKey.KeyId, keyAlgorithm,
                    hashAlgorithm, creationTime * 1000L, fingerPrint, sigValues));
        }
コード例 #12
0
 public DsaSecretBcpgKey(BcpgInputStream bcpgIn)
 {
     x = new MPInteger(bcpgIn);
 }
コード例 #13
0
ファイル: PgpPublicKey.cs プロジェクト: hjgode/iTextSharpCF
        private void Init()
        {
            IBcpgKey key = publicPk.Key;

            if (publicPk.Version <= 3)
            {
                RsaPublicBcpgKey rK = (RsaPublicBcpgKey) key;

                this.keyId = rK.Modulus.LongValue;

                try
                {
                    IDigest digest = DigestUtilities.GetDigest("MD5");

                    byte[] bytes = new MPInteger(rK.Modulus).GetEncoded();
                    digest.BlockUpdate(bytes, 2, bytes.Length - 2);

                    bytes = new MPInteger(rK.PublicExponent).GetEncoded();
                    digest.BlockUpdate(bytes, 2, bytes.Length - 2);

                    this.fingerprint = DigestUtilities.DoFinal(digest);
                }
                //catch (NoSuchAlgorithmException)
                catch (Exception)
                {
                    throw new IOException("can't find MD5");
                }

                this.keyStrength = rK.Modulus.BitLength;
            }
            else
            {
                byte[] kBytes = publicPk.GetEncodedContents();

                try
                {
                    IDigest digest = DigestUtilities.GetDigest("SHA1");

                    digest.Update(0x99);
                    digest.Update((byte)(kBytes.Length >> 8));
                    digest.Update((byte)kBytes.Length);
                    digest.BlockUpdate(kBytes, 0, kBytes.Length);
                    this.fingerprint = DigestUtilities.DoFinal(digest);
                }
                //catch (NoSuchAlgorithmException)
                catch (Exception)
                {
                    throw new IOException("can't find SHA1");
                }

                this.keyId = (long)(((ulong)fingerprint[fingerprint.Length - 8] << 56)
                    | ((ulong)fingerprint[fingerprint.Length - 7] << 48)
                    | ((ulong)fingerprint[fingerprint.Length - 6] << 40)
                    | ((ulong)fingerprint[fingerprint.Length - 5] << 32)
                    | ((ulong)fingerprint[fingerprint.Length - 4] << 24)
                    | ((ulong)fingerprint[fingerprint.Length - 3] << 16)
                    | ((ulong)fingerprint[fingerprint.Length - 2] << 8)
                    | (ulong)fingerprint[fingerprint.Length - 1]);

                if (key is RsaPublicBcpgKey)
                {
                    this.keyStrength = ((RsaPublicBcpgKey)key).Modulus.BitLength;
                }
                else if (key is DsaPublicBcpgKey)
                {
                    this.keyStrength = ((DsaPublicBcpgKey)key).P.BitLength;
                }
                else if (key is ElGamalPublicBcpgKey)
                {
                    this.keyStrength = ((ElGamalPublicBcpgKey)key).P.BitLength;
                }
            }
        }
コード例 #14
0
            private byte[] EncryptSessionInfo(byte[] sessionInfo, SecureRandom random)
            {
                if (pubKey.Algorithm != PublicKeyAlgorithmTag.ECDH)
                {
                    IBufferedCipher c;
                    switch (pubKey.Algorithm)
                    {
                    case PublicKeyAlgorithmTag.RsaEncrypt:
                    case PublicKeyAlgorithmTag.RsaGeneral:
                        c = CipherUtilities.GetCipher("RSA//PKCS1Padding");
                        break;

                    case PublicKeyAlgorithmTag.ElGamalEncrypt:
                    case PublicKeyAlgorithmTag.ElGamalGeneral:
                        c = CipherUtilities.GetCipher("ElGamal/ECB/PKCS1Padding");
                        break;

                    case PublicKeyAlgorithmTag.Dsa:
                        throw new PgpException("Can't use DSA for encryption.");

                    case PublicKeyAlgorithmTag.ECDsa:
                        throw new PgpException("Can't use ECDSA for encryption.");

                    default:
                        throw new PgpException("unknown asymmetric algorithm: " + pubKey.Algorithm);
                    }

                    AsymmetricKeyParameter akp = pubKey.GetKey();
                    c.Init(true, new ParametersWithRandom(akp, random));
                    return(c.DoFinal(sessionInfo));
                }

                ECDHPublicBcpgKey ecKey = (ECDHPublicBcpgKey)pubKey.PublicKeyPacket.Key;

                // Generate the ephemeral key pair
                IAsymmetricCipherKeyPairGenerator gen = GeneratorUtilities.GetKeyPairGenerator("ECDH");

                gen.Init(new ECKeyGenerationParameters(ecKey.CurveOid, random));

                AsymmetricCipherKeyPair ephKp   = gen.GenerateKeyPair();
                ECPrivateKeyParameters  ephPriv = (ECPrivateKeyParameters)ephKp.Private;
                ECPublicKeyParameters   ephPub  = (ECPublicKeyParameters)ephKp.Public;

                ECPublicKeyParameters pub = (ECPublicKeyParameters)pubKey.GetKey();
                ECPoint S = pub.Q.Multiply(ephPriv.D).Normalize();

                KeyParameter key = new KeyParameter(Rfc6637Utilities.CreateKey(pubKey.PublicKeyPacket, S));

                IWrapper w = PgpUtilities.CreateWrapper(ecKey.SymmetricKeyAlgorithm);

                w.Init(true, new ParametersWithRandom(key, random));

                byte[] paddedSessionData = PgpPad.PadSessionData(sessionInfo);

                byte[] C  = w.Wrap(paddedSessionData, 0, paddedSessionData.Length);
                byte[] VB = new MPInteger(new BigInteger(1, ephPub.Q.GetEncoded(false))).GetEncoded();

                byte[] rv = new byte[VB.Length + 1 + C.Length];

                Array.Copy(VB, 0, rv, 0, VB.Length);
                rv[VB.Length] = (byte)C.Length;
                Array.Copy(C, 0, rv, VB.Length + 1, C.Length);

                return(rv);
            }
コード例 #15
0
 public RsaPublicBcpgKey(BigInteger n, BigInteger e)
 {
     this.n = new MPInteger(n);
     this.e = new MPInteger(e);
 }
コード例 #16
0
 public ElGamalPublicBcpgKey(BigInteger p, BigInteger g, BigInteger y)
 {
     this.p = new MPInteger(p);
     this.g = new MPInteger(g);
     this.y = new MPInteger(y);
 }
コード例 #17
0
 public ElGamalPublicBcpgKey(BcpgInputStream bcpgIn)
 {
     p = new MPInteger(bcpgIn);
     g = new MPInteger(bcpgIn);
     y = new MPInteger(bcpgIn);
 }
コード例 #18
0
        /// <summary>Return a signature object containing the current signature state.</summary>
        public PgpSignature Generate()
        {
            MPInteger[] sigValues;
            int version = 4;
            MemoryStream sOut = new MemoryStream();

            //            int index = 0;
            //
            //			if (!creationTimeFound)
            //            {
            //                hashed[index++] = new SignatureCreationTime(false, DateTime.UtcNow);
            //            }
            //
            //			if (!issuerKeyIDFound)
            //            {
            //                hashed[index++] = new IssuerKeyId(false, privKey.KeyId);
            //            }
            SignatureSubpacket[] hPkts, unhPkts;

            if (!packetPresent(hashed, SignatureSubpacketTag.CreationTime))
            {
                hPkts = insertSubpacket(hashed, new SignatureCreationTime(false, DateTime.UtcNow));
            }
            else
            {
                hPkts = hashed;
            }

            if (!packetPresent(hashed, SignatureSubpacketTag.IssuerKeyId)
                && !packetPresent(unhashed, SignatureSubpacketTag.IssuerKeyId))
            {
                unhPkts = insertSubpacket(unhashed, new IssuerKeyId(false, privKey.KeyId));
            }
            else
            {
                unhPkts = unhashed;
            }

            try
            {
                sOut.WriteByte((byte)version);
                sOut.WriteByte((byte)signatureType);
                sOut.WriteByte((byte)keyAlgorithm);
                sOut.WriteByte((byte)hashAlgorithm);

                MemoryStream hOut = new MemoryStream();

                for (int i = 0; i != hPkts.Length; i++)
                {
                    hPkts[i].Encode(hOut);
                }

                byte[] data = hOut.ToArray();

                sOut.WriteByte((byte)(data.Length >> 8));
                sOut.WriteByte((byte)data.Length);
                sOut.Write(data, 0, data.Length);
            }
            catch (IOException e)
            {
                throw new PgpException("exception encoding hashed data.", e);
            }

            byte[] hData = sOut.ToArray();

            sig.BlockUpdate(hData, 0, hData.Length);
            dig.BlockUpdate(hData, 0, hData.Length);

            sOut = new MemoryStream();
            sOut.WriteByte((byte)version);
            sOut.WriteByte(0xff);
            sOut.WriteByte((byte)(hData.Length >> 24));
            sOut.WriteByte((byte)(hData.Length >> 16));
            sOut.WriteByte((byte)(hData.Length >> 8));
            sOut.WriteByte((byte)(hData.Length));

            hData = sOut.ToArray();

            sig.BlockUpdate(hData, 0, hData.Length);
            dig.BlockUpdate(hData, 0, hData.Length);

            byte[] sigBytes = sig.GenerateSignature();
            byte[] digest = DigestUtilities.DoFinal(dig);
            byte[] fingerPrint = new byte[] { digest[0], digest[1] };

            if (keyAlgorithm == PublicKeyAlgorithmTag.RsaSign
                || keyAlgorithm == PublicKeyAlgorithmTag.RsaGeneral)    // an RSA signature
            {
                sigValues = new MPInteger[]{ new MPInteger(new BigInteger(1, sigBytes)) };
            }
            else
            {
                sigValues = PgpUtilities.DsaSigToMpi(sigBytes);
            }

            return new PgpSignature(
                new SignaturePacket(signatureType, privKey.KeyId, keyAlgorithm,
                    hashAlgorithm, hPkts, unhPkts, fingerPrint, sigValues));
        }
コード例 #19
0
 public DsaSecretBcpgKey(BigInteger x)
 {
     this.x = new MPInteger(x);
 }
コード例 #20
0
        /// <summary>Return a signature object containing the current signature state.</summary>
        public PgpSignature Generate()
        {
            MPInteger[]  sigValues;
            int          version = 4;
            MemoryStream sOut    = new MemoryStream();

//            int index = 0;
//
//			if (!creationTimeFound)
//            {
//                hashed[index++] = new SignatureCreationTime(false, DateTime.UtcNow);
//            }
//
//			if (!issuerKeyIDFound)
//            {
//                hashed[index++] = new IssuerKeyId(false, privKey.KeyId);
//            }
            SignatureSubpacket[] hPkts, unhPkts;

            if (!packetPresent(hashed, SignatureSubpacketTag.CreationTime))
            {
                hPkts = insertSubpacket(hashed, new SignatureCreationTime(false, DateTime.UtcNow));
            }
            else
            {
                hPkts = hashed;
            }

            if (!packetPresent(hashed, SignatureSubpacketTag.IssuerKeyId) &&
                !packetPresent(unhashed, SignatureSubpacketTag.IssuerKeyId))
            {
                unhPkts = insertSubpacket(unhashed, new IssuerKeyId(false, privKey.KeyId));
            }
            else
            {
                unhPkts = unhashed;
            }

            try
            {
                sOut.WriteByte((byte)version);
                sOut.WriteByte((byte)signatureType);
                sOut.WriteByte((byte)keyAlgorithm);
                sOut.WriteByte((byte)hashAlgorithm);

                MemoryStream hOut = new MemoryStream();

                for (int i = 0; i != hPkts.Length; i++)
                {
                    hPkts[i].Encode(hOut);
                }

                byte[] data = hOut.ToArray();

                sOut.WriteByte((byte)(data.Length >> 8));
                sOut.WriteByte((byte)data.Length);
                sOut.Write(data, 0, data.Length);
            }
            catch (IOException e)
            {
                throw new PgpException("exception encoding hashed data.", e);
            }

            byte[] hData = sOut.ToArray();

            sig.BlockUpdate(hData, 0, hData.Length);
            dig.BlockUpdate(hData, 0, hData.Length);

            sOut = new MemoryStream();
            sOut.WriteByte((byte)version);
            sOut.WriteByte((byte)0xff);
            sOut.WriteByte((byte)(hData.Length >> 24));
            sOut.WriteByte((byte)(hData.Length >> 16));
            sOut.WriteByte((byte)(hData.Length >> 8));
            sOut.WriteByte((byte)(hData.Length));

            hData = sOut.ToArray();

            sig.BlockUpdate(hData, 0, hData.Length);
            dig.BlockUpdate(hData, 0, hData.Length);

            byte[] sigBytes    = sig.GenerateSignature();
            byte[] digest      = DigestUtilities.DoFinal(dig);
            byte[] fingerPrint = new byte[] { digest[0], digest[1] };

            if (keyAlgorithm == PublicKeyAlgorithmTag.RsaSign ||
                keyAlgorithm == PublicKeyAlgorithmTag.RsaGeneral)       // an RSA signature
            {
                sigValues = new MPInteger[] { new MPInteger(new BigInteger(1, sigBytes)) };
            }
            else
            {
                sigValues = PgpUtilities.DsaSigToMpi(sigBytes);
            }

            return(new PgpSignature(
                       new SignaturePacket(signatureType, privKey.KeyId, keyAlgorithm,
                                           hashAlgorithm, hPkts, unhPkts, fingerPrint, sigValues)));
        }
コード例 #21
0
 public ElGamalSecretBcpgKey(BigInteger x)
 {
     this.x = new MPInteger(x);
 }
コード例 #22
0
 public ElGamalSecretBcpgKey(BcpgInputStream bcpgIn)
 {
     x = new MPInteger(bcpgIn);
 }
コード例 #23
0
 public RsaPublicBcpgKey(BcpgInputStream bcpgIn)
 {
     n = new MPInteger(bcpgIn);
     e = new MPInteger(bcpgIn);
 }
コード例 #24
0
        private void Init()
        {
            IBcpgKey key = publicPk.Key;

            if (publicPk.Version <= 3)
            {
                RsaPublicBcpgKey rK = (RsaPublicBcpgKey)key;

                this.keyId = rK.Modulus.LongValue;

                try
                {
                    IDigest digest = DigestUtilities.GetDigest("MD5");

                    byte[] bytes = new MPInteger(rK.Modulus).GetEncoded();
                    digest.BlockUpdate(bytes, 2, bytes.Length - 2);

                    bytes = new MPInteger(rK.PublicExponent).GetEncoded();
                    digest.BlockUpdate(bytes, 2, bytes.Length - 2);

                    this.fingerprint = DigestUtilities.DoFinal(digest);
                }
                //catch (NoSuchAlgorithmException)
                catch (Exception)
                {
                    throw new IOException("can't find MD5");
                }

                this.keyStrength = rK.Modulus.BitLength;
            }
            else
            {
                byte[] kBytes = publicPk.GetEncodedContents();

                try
                {
                    IDigest digest = DigestUtilities.GetDigest("SHA1");

                    digest.Update((byte)0x99);
                    digest.Update((byte)(kBytes.Length >> 8));
                    digest.Update((byte)kBytes.Length);
                    digest.BlockUpdate(kBytes, 0, kBytes.Length);
                    this.fingerprint = DigestUtilities.DoFinal(digest);
                }
                //catch (NoSuchAlgorithmException)
                catch (Exception)
                {
                    throw new IOException("can't find SHA1");
                }

                this.keyId = (long)(((ulong)fingerprint[fingerprint.Length - 8] << 56)
                                    | ((ulong)fingerprint[fingerprint.Length - 7] << 48)
                                    | ((ulong)fingerprint[fingerprint.Length - 6] << 40)
                                    | ((ulong)fingerprint[fingerprint.Length - 5] << 32)
                                    | ((ulong)fingerprint[fingerprint.Length - 4] << 24)
                                    | ((ulong)fingerprint[fingerprint.Length - 3] << 16)
                                    | ((ulong)fingerprint[fingerprint.Length - 2] << 8)
                                    | (ulong)fingerprint[fingerprint.Length - 1]);

                if (key is RsaPublicBcpgKey)
                {
                    this.keyStrength = ((RsaPublicBcpgKey)key).Modulus.BitLength;
                }
                else if (key is DsaPublicBcpgKey)
                {
                    this.keyStrength = ((DsaPublicBcpgKey)key).P.BitLength;
                }
                else if (key is ElGamalPublicBcpgKey)
                {
                    this.keyStrength = ((ElGamalPublicBcpgKey)key).P.BitLength;
                }
            }
        }
コード例 #25
0
    internal SignaturePacket(BcpgInputStream bcpgIn)
    {
        version = bcpgIn.ReadByte();
        if (version == 3 || version == 2)
        {
            bcpgIn.ReadByte();
            signatureType = bcpgIn.ReadByte();
            creationTime  = (((long)bcpgIn.ReadByte() << 24) | ((long)bcpgIn.ReadByte() << 16) | ((long)bcpgIn.ReadByte() << 8) | (uint)bcpgIn.ReadByte()) * 1000;
            keyId        |= (long)bcpgIn.ReadByte() << 56;
            keyId        |= (long)bcpgIn.ReadByte() << 48;
            keyId        |= (long)bcpgIn.ReadByte() << 40;
            keyId        |= (long)bcpgIn.ReadByte() << 32;
            keyId        |= (long)bcpgIn.ReadByte() << 24;
            keyId        |= (long)bcpgIn.ReadByte() << 16;
            keyId        |= (long)bcpgIn.ReadByte() << 8;
            keyId        |= (uint)bcpgIn.ReadByte();
            keyAlgorithm  = (PublicKeyAlgorithmTag)bcpgIn.ReadByte();
            hashAlgorithm = (HashAlgorithmTag)bcpgIn.ReadByte();
        }
        else
        {
            if (version != 4)
            {
                throw new Exception("unsupported version: " + version);
            }
            signatureType = bcpgIn.ReadByte();
            keyAlgorithm  = (PublicKeyAlgorithmTag)bcpgIn.ReadByte();
            hashAlgorithm = (HashAlgorithmTag)bcpgIn.ReadByte();
            int    num    = (bcpgIn.ReadByte() << 8) | bcpgIn.ReadByte();
            byte[] buffer = new byte[num];
            bcpgIn.ReadFully(buffer);
            SignatureSubpacketsParser signatureSubpacketsParser = new SignatureSubpacketsParser(new MemoryStream(buffer, writable: false));
            IList list = Platform.CreateArrayList();
            SignatureSubpacket value;
            while ((value = signatureSubpacketsParser.ReadPacket()) != null)
            {
                list.Add(value);
            }
            hashedData = new SignatureSubpacket[list.Count];
            for (int i = 0; i != hashedData.Length; i++)
            {
                SignatureSubpacket signatureSubpacket = (SignatureSubpacket)list[i];
                if (signatureSubpacket is IssuerKeyId)
                {
                    keyId = ((IssuerKeyId)signatureSubpacket).KeyId;
                }
                else if (signatureSubpacket is SignatureCreationTime)
                {
                    creationTime = DateTimeUtilities.DateTimeToUnixMs(((SignatureCreationTime)signatureSubpacket).GetTime());
                }
                hashedData[i] = signatureSubpacket;
            }
            int    num2    = (bcpgIn.ReadByte() << 8) | bcpgIn.ReadByte();
            byte[] buffer2 = new byte[num2];
            bcpgIn.ReadFully(buffer2);
            signatureSubpacketsParser = new SignatureSubpacketsParser(new MemoryStream(buffer2, writable: false));
            list.Clear();
            while ((value = signatureSubpacketsParser.ReadPacket()) != null)
            {
                list.Add(value);
            }
            unhashedData = new SignatureSubpacket[list.Count];
            for (int j = 0; j != unhashedData.Length; j++)
            {
                SignatureSubpacket signatureSubpacket2 = (SignatureSubpacket)list[j];
                if (signatureSubpacket2 is IssuerKeyId)
                {
                    keyId = ((IssuerKeyId)signatureSubpacket2).KeyId;
                }
                unhashedData[j] = signatureSubpacket2;
            }
        }
        fingerprint = new byte[2];
        bcpgIn.ReadFully(fingerprint);
        switch (keyAlgorithm)
        {
        case PublicKeyAlgorithmTag.RsaGeneral:
        case PublicKeyAlgorithmTag.RsaSign:
        {
            MPInteger mPInteger8 = new MPInteger(bcpgIn);
            signature = new MPInteger[1]
            {
                mPInteger8
            };
            return;
        }

        case PublicKeyAlgorithmTag.Dsa:
        {
            MPInteger mPInteger6 = new MPInteger(bcpgIn);
            MPInteger mPInteger7 = new MPInteger(bcpgIn);
            signature = new MPInteger[2]
            {
                mPInteger6,
                mPInteger7
            };
            return;
        }

        case PublicKeyAlgorithmTag.ElGamalEncrypt:
        case PublicKeyAlgorithmTag.ElGamalGeneral:
        {
            MPInteger mPInteger3 = new MPInteger(bcpgIn);
            MPInteger mPInteger4 = new MPInteger(bcpgIn);
            MPInteger mPInteger5 = new MPInteger(bcpgIn);
            signature = new MPInteger[3]
            {
                mPInteger3,
                mPInteger4,
                mPInteger5
            };
            return;
        }

        case PublicKeyAlgorithmTag.ECDsa:
        {
            MPInteger mPInteger  = new MPInteger(bcpgIn);
            MPInteger mPInteger2 = new MPInteger(bcpgIn);
            signature = new MPInteger[2]
            {
                mPInteger,
                mPInteger2
            };
            return;
        }
        }
        if (keyAlgorithm >= PublicKeyAlgorithmTag.Experimental_1 && keyAlgorithm <= PublicKeyAlgorithmTag.Experimental_11)
        {
            signature = null;
            MemoryStream memoryStream = new MemoryStream();
            int          num3;
            while ((num3 = bcpgIn.ReadByte()) >= 0)
            {
                memoryStream.WriteByte((byte)num3);
            }
            signatureEncoding = memoryStream.ToArray();
            return;
        }
        throw new IOException("unknown signature key algorithm: " + keyAlgorithm);
    }
コード例 #26
0
            private byte[] EncryptSessionInfo(byte[] sessionInfo, SecureRandom random)
            {
                if (pubKey.Algorithm != PublicKeyAlgorithmTag.ECDH)
                {
                    IBufferedCipher c;
				    switch (pubKey.Algorithm)
                    {
                        case PublicKeyAlgorithmTag.RsaEncrypt:
                        case PublicKeyAlgorithmTag.RsaGeneral:
                            c = CipherUtilities.GetCipher("RSA//PKCS1Padding");
                            break;
                        case PublicKeyAlgorithmTag.ElGamalEncrypt:
                        case PublicKeyAlgorithmTag.ElGamalGeneral:
                            c = CipherUtilities.GetCipher("ElGamal/ECB/PKCS1Padding");
                            break;
                        case PublicKeyAlgorithmTag.Dsa:
                            throw new PgpException("Can't use DSA for encryption.");
                        case PublicKeyAlgorithmTag.ECDsa:
                            throw new PgpException("Can't use ECDSA for encryption.");
                        default:
                            throw new PgpException("unknown asymmetric algorithm: " + pubKey.Algorithm);
                    }

                    AsymmetricKeyParameter akp = pubKey.GetKey();
				    c.Init(true, new ParametersWithRandom(akp, random));
                    return c.DoFinal(sessionInfo);
                }

                ECDHPublicBcpgKey ecKey = (ECDHPublicBcpgKey)pubKey.PublicKeyPacket.Key;

                // Generate the ephemeral key pair
                IAsymmetricCipherKeyPairGenerator gen = GeneratorUtilities.GetKeyPairGenerator("ECDH");
                gen.Init(new ECKeyGenerationParameters(ecKey.CurveOid, random));

                AsymmetricCipherKeyPair ephKp = gen.GenerateKeyPair();
                ECPrivateKeyParameters ephPriv = (ECPrivateKeyParameters)ephKp.Private;
                ECPublicKeyParameters ephPub = (ECPublicKeyParameters)ephKp.Public;

                ECPublicKeyParameters pub = (ECPublicKeyParameters)pubKey.GetKey();
                ECPoint S = pub.Q.Multiply(ephPriv.D).Normalize();

                KeyParameter key = new KeyParameter(Rfc6637Utilities.CreateKey(pubKey.PublicKeyPacket, S));

                IWrapper w = PgpUtilities.CreateWrapper(ecKey.SymmetricKeyAlgorithm);
                w.Init(true, new ParametersWithRandom(key, random));

                byte[] paddedSessionData = PgpPad.PadSessionData(sessionInfo);

                byte[] C = w.Wrap(paddedSessionData, 0, paddedSessionData.Length);
                byte[] VB = new MPInteger(new BigInteger(1, ephPub.Q.GetEncoded(false))).GetEncoded();

                byte[] rv = new byte[VB.Length + 1 + C.Length];

                Array.Copy(VB, 0, rv, 0, VB.Length);
                rv[VB.Length] = (byte)C.Length;
                Array.Copy(C, 0, rv, VB.Length + 1, C.Length);

                return rv;
            }