RsaDigestSigner.cs :  » PDF » iTextSharp » Org » BouncyCastle » Crypto » Signers » C# / CSharp Open Source

Home
C# / CSharp Open Source
1.2.6.4 mono .net core
2.2.6.4 mono core
3.Aspect Oriented Frameworks
4.Bloggers
5.Build Systems
6.Business Application
7.Charting Reporting Tools
8.Chat Servers
9.Code Coverage Tools
10.Content Management Systems CMS
11.CRM ERP
12.Database
13.Development
14.Email
15.Forum
16.Game
17.GIS
18.GUI
19.IDEs
20.Installers Generators
21.Inversion of Control Dependency Injection
22.Issue Tracking
23.Logging Tools
24.Message
25.Mobile
26.Network Clients
27.Network Servers
28.Office
29.PDF
30.Persistence Frameworks
31.Portals
32.Profilers
33.Project Management
34.RSS RDF
35.Rule Engines
36.Script
37.Search Engines
38.Sound Audio
39.Source Control
40.SQL Clients
41.Template Engines
42.Testing
43.UML
44.Web Frameworks
45.Web Service
46.Web Testing
47.Wiki Engines
48.Windows Presentation Foundation
49.Workflows
50.XML Parsers
C# / C Sharp
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source » PDF » iTextSharp 
iTextSharp » Org » BouncyCastle » Crypto » Signers » RsaDigestSigner.cs
using System;
using System.Collections;
using System.IO;
using System.Text;

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Nist;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.TeleTrust;
using Org.BouncyCastle.Asn1.Utilities;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Signers;
using Org.BouncyCastle.Security;

namespace Org.BouncyCastle.Crypto.Signers{
    public class RsaDigestSigner
    : ISigner
    {
        private readonly IAsymmetricBlockCipher rsaEngine = new Pkcs1Encoding(new RsaBlindedEngine());
        private readonly AlgorithmIdentifier algId;
    private readonly IDigest digest;
    private bool forSigning;

    private static readonly Hashtable oidMap = new Hashtable();

    /// <summary>
        /// Load oid table.
        /// </summary>
        static RsaDigestSigner()
        {
            oidMap["RIPEMD128"] = TeleTrusTObjectIdentifiers.RipeMD128;
            oidMap["RIPEMD160"] = TeleTrusTObjectIdentifiers.RipeMD160;
            oidMap["RIPEMD256"] = TeleTrusTObjectIdentifiers.RipeMD256;

            oidMap["SHA-1"] = X509ObjectIdentifiers.IdSha1;
            oidMap["SHA-224"] = NistObjectIdentifiers.IdSha224;
            oidMap["SHA-256"] = NistObjectIdentifiers.IdSha256;
            oidMap["SHA-384"] = NistObjectIdentifiers.IdSha384;
            oidMap["SHA-512"] = NistObjectIdentifiers.IdSha512;

            oidMap["MD2"] = PkcsObjectIdentifiers.MD2;
            oidMap["MD4"] = PkcsObjectIdentifiers.MD4;
            oidMap["MD5"] = PkcsObjectIdentifiers.MD5;
        }

    public RsaDigestSigner(
      IDigest digest)
        {
            this.digest = digest;

      string algName = digest.AlgorithmName;
      if (algName.Equals("NULL"))
      {
        this.algId = null;
      }
      else
      {
        this.algId = new AlgorithmIdentifier(
          (DerObjectIdentifier)oidMap[digest.AlgorithmName], DerNull.Instance);
      }
        }

    public string AlgorithmName
        {
            get { return digest.AlgorithmName + "withRSA"; }
        }

    /**
         * Initialise the signer for signing or verification.
         *
         * @param forSigning true if for signing, false otherwise
         * @param param necessary parameters.
         */
        public void Init(
      bool        forSigning,
      ICipherParameters  parameters)
        {
            this.forSigning = forSigning;
            AsymmetricKeyParameter k;

            if (parameters is ParametersWithRandom)
            {
                k = (AsymmetricKeyParameter)((ParametersWithRandom)parameters).Parameters;
            }
            else
            {
                k = (AsymmetricKeyParameter)parameters;
            }

            if (forSigning && !k.IsPrivate)
                throw new InvalidKeyException("Signing requires private key.");

      if (!forSigning && k.IsPrivate)
                throw new InvalidKeyException("Verification requires public key.");

      Reset();

            rsaEngine.Init(forSigning, parameters);
        }

        /**
         * update the internal digest with the byte b
         */
        public void Update(
      byte input)
        {
            digest.Update(input);
        }

        /**
         * update the internal digest with the byte array in
         */
        public void BlockUpdate(
      byte[]  input,
      int    inOff,
      int    length)
        {
            digest.BlockUpdate(input, inOff, length);
        }

        /**
         * Generate a signature for the message we've been loaded with using
         * the key we were initialised with.
         */
        public byte[] GenerateSignature()
        {
            if (!forSigning)
                throw new InvalidOperationException("RsaDigestSigner not initialised for signature generation.");

      byte[] hash = new byte[digest.GetDigestSize()];
            digest.DoFinal(hash, 0);

      byte[] data = DerEncode(hash);
            return rsaEngine.ProcessBlock(data, 0, data.Length);
        }

    /**
         * return true if the internal state represents the signature described
         * in the passed in array.
         */
        public bool VerifySignature(
      byte[] signature)
        {
      if (forSigning)
        throw new InvalidOperationException("RsaDigestSigner not initialised for verification");

      byte[] hash = new byte[digest.GetDigestSize()];
      digest.DoFinal(hash, 0);

      byte[] sig;
      byte[] expected;

      try
      {
        sig = rsaEngine.ProcessBlock(signature, 0, signature.Length);
        expected = DerEncode(hash);
      }
      catch (Exception)
      {
        return false;
      }

      if (sig.Length == expected.Length)
      {
        for (int i = 0; i < sig.Length; i++)
        {
          if (sig[i] != expected[i])
          {
            return false;
          }
        }
      }
      else if (sig.Length == expected.Length - 2)  // NULL left out
      {
        int sigOffset = sig.Length - hash.Length - 2;
        int expectedOffset = expected.Length - hash.Length - 2;

        expected[1] -= 2;      // adjust lengths
        expected[3] -= 2;

        for (int i = 0; i < hash.Length; i++)
        {
          if (sig[sigOffset + i] != expected[expectedOffset + i])  // check hash
          {
            return false;
          }
        }

        for (int i = 0; i < sigOffset; i++)
        {
          if (sig[i] != expected[i])  // check header less NULL
          {
            return false;
          }
        }
      }
      else
      {
        return false;
      }

      return true;
        }

        public void Reset()
        {
            digest.Reset();
        }

    private byte[] DerEncode(byte[] hash)
    {
      if (algId == null)
      {
        // For raw RSA, the DigestInfo must be prepared externally
        return hash;
      }

      DigestInfo dInfo = new DigestInfo(algId, hash);

      return dInfo.GetDerEncoded();
    }
    }
}
www.java2v.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.