elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


  Mostrar Temas
Páginas: [1]
1  Programación / Scripting / Imprimir resultado Python en: 29 Noviembre 2016, 19:19 pm
Hola muy buenas. Quería saber como imprimir el resultado de "y","g","p","q","x" de este programa en python del DSA:

Código
  1.  
  2. # -*- coding: utf-8 -*-
  3. #
  4. #  PublicKey/DSA.py : DSA signature primitive
  5. #
  6. # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
  7. #
  8. # ===================================================================
  9. # The contents of this file are dedicated to the public domain.  To
  10. # the extent that dedication to the public domain is not available,
  11. # everyone is granted a worldwide, perpetual, royalty-free,
  12. # non-exclusive license to exercise all rights associated with the
  13. # contents of this file for any purpose whatsoever.
  14. # No rights are reserved.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  20. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  21. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. # SOFTWARE.
  24. # ===================================================================
  25.  
  26. """DSA public-key signature algorithm.
  27.  
  28. DSA_ is a widespread public-key signature algorithm. Its security is
  29. based on the discrete logarithm problem (DLP_). Given a cyclic
  30. group, a generator *g*, and an element *h*, it is hard
  31. to find an integer *x* such that *g^x = h*. The problem is believed
  32. to be difficult, and it has been proved such (and therefore secure) for
  33. more than 30 years.
  34.  
  35. The group is actually a sub-group over the integers modulo *p*, with *p* prime.
  36. The sub-group order is *q*, which is prime too; it always holds that *(p-1)* is a multiple of *q*.
  37. The cryptographic strength is linked to the magnitude of *p* and *q*.
  38. The signer holds a value *x* (*0<x<q-1*) as private key, and its public
  39. key (*y* where *y=g^x mod p*) is distributed.
  40.  
  41. In 2012, a sufficient size is deemed to be 2048 bits for *p* and 256 bits for *q*.
  42. For more information, see the most recent ECRYPT_ report.
  43.  
  44. DSA is reasonably secure for new designs.
  45.  
  46. The algorithm can only be used for authentication (digital signature).
  47. DSA cannot be used for confidentiality (encryption).
  48.  
  49. The values *(p,q,g)* are called *domain parameters*;
  50. they are not sensitive but must be shared by both parties (the signer and the verifier).
  51. Different signers can share the same domain parameters with no security
  52. concerns.
  53.  
  54. The DSA signature is twice as big as the size of *q* (64 bytes if *q* is 256 bit
  55. long).
  56.  
  57. This module provides facilities for generating new DSA keys and for constructing
  58. them from known components. DSA keys allows you to perform basic signing and
  59. verification.
  60.  
  61.    >>> from Crypto.Random import random
  62.    >>> from Crypto.PublicKey import DSA
  63.    >>> from Crypto.Hash import SHA
  64.    >>>
  65.    >>> message = "Hello"
  66.    >>> key = DSA.generate(1024)
  67.    >>> h = SHA.new(message).digest()
  68.    >>> k = random.StrongRandom().randint(1,key.q-1)
  69.    >>> sig = key.sign(h,k)
  70.    >>> ...
  71.    >>> if key.verify(h,sig):
  72.    >>>     print "OK"
  73.    >>> else:
  74.    >>>     print "Incorrect signature"
  75.  
  76. .. _DSA: http://en.wikipedia.org/wiki/Digital_Signature_Algorithm
  77. .. _DLP: http://www.cosic.esat.kuleuven.be/publications/talk-78.pdf
  78. .. _ECRYPT: http://www.ecrypt.eu.org/documents/D.SPA.17.pdf
  79. """
  80.  
  81. __revision__ = "$Id$"
  82.  
  83. __all__ = ['generate', 'construct', 'error', 'DSAImplementation', '_DSAobj']
  84.  
  85. import sys
  86. if sys.version_info[0] == 2 and sys.version_info[1] == 1:
  87.    from Crypto.Util.py21compat import *
  88.  
  89. from Crypto.PublicKey import _DSA, _slowmath, pubkey
  90. from Crypto import Random
  91.  
  92. try:
  93.    from Crypto.PublicKey import _fastmath
  94. except ImportError:
  95.    _fastmath = None
  96.  
  97. class _DSAobj(pubkey.pubkey):
  98.    """Class defining an actual DSA key.
  99.  
  100.    :undocumented: __getstate__, __setstate__, __repr__, __getattr__
  101.    """
  102.    #: Dictionary of DSA parameters.
  103.    #:
  104.    #: A public key will only have the following entries:
  105.    #:
  106.    #:  - **y**, the public key.
  107.    #:  - **g**, the generator.
  108.    #:  - **p**, the modulus.
  109.    #:  - **q**, the order of the sub-group.
  110.    #:
  111.    #: A private key will also have:
  112.    #:
  113.    #:  - **x**, the private key.
  114.    keydata = ['y', 'g', 'p', 'q', 'x']
  115.  
  116.    def __init__(self, implementation, key):
  117.        self.implementation = implementation
  118.        self.key = key
  119.  
  120.    def __getattr__(self, attrname):
  121.        if attrname in self.keydata:
  122.            # For backward compatibility, allow the user to get (not set) the
  123.            # DSA key parameters directly from this object.
  124.            return getattr(self.key, attrname)
  125.        else:
  126.            raise AttributeError("%s object has no %r attribute" % (self.__class__.__name__, attrname,))
  127.  
  128.    def sign(self, M, K):
  129.        """Sign a piece of data with DSA.
  130.  
  131.        :Parameter M: The piece of data to sign with DSA. It may
  132.         not be longer in bit size than the sub-group order (*q*).
  133.        :Type M: byte string or long
  134.  
  135.        :Parameter K: A secret number, chosen randomly in the closed
  136.         range *[1,q-1]*.
  137.        :Type K: long (recommended) or byte string (not recommended)
  138.  
  139.        :attention: selection of *K* is crucial for security. Generating a
  140.         random number larger than *q* and taking the modulus by *q* is
  141.         **not** secure, since smaller values will occur more frequently.
  142.         Generating a random number systematically smaller than *q-1*
  143.         (e.g. *floor((q-1)/8)* random bytes) is also **not** secure. In general,
  144.         it shall not be possible for an attacker to know the value of `any
  145.         bit of K`__.
  146.  
  147.        :attention: The number *K* shall not be reused for any other
  148.         operation and shall be discarded immediately.
  149.  
  150.        :attention: M must be a digest cryptographic hash, otherwise
  151.         an attacker may mount an existential forgery attack.
  152.  
  153.        :Return: A tuple with 2 longs.
  154.  
  155.        .. __: http://www.di.ens.fr/~pnguyen/pub_NgSh00.htm
  156.        """
  157.        return pubkey.pubkey.sign(self, M, K)
  158.  
  159.    def verify(self, M, signature):
  160.        """Verify the validity of a DSA signature.
  161.  
  162.        :Parameter M: The expected message.
  163.        :Type M: byte string or long
  164.  
  165.        :Parameter signature: The DSA signature to verify.
  166.        :Type signature: A tuple with 2 longs as return by `sign`
  167.  
  168.        :Return: True if the signature is correct, False otherwise.
  169.        """
  170.        return pubkey.pubkey.verify(self, M, signature)
  171.  
  172.    def _encrypt(self, c, K):
  173.        raise TypeError("DSA cannot encrypt")
  174.  
  175.    def _decrypt(self, c):
  176.        raise TypeError("DSA cannot decrypt")
  177.  
  178.    def _blind(self, m, r):
  179.        raise TypeError("DSA cannot blind")
  180.  
  181.    def _unblind(self, m, r):
  182.        raise TypeError("DSA cannot unblind")
  183.  
  184.    def _sign(self, m, k):
  185.        return self.key._sign(m, k)
  186.  
  187.    def _verify(self, m, sig):
  188.        (r, s) = sig
  189.        return self.key._verify(m, r, s)
  190.  
  191.    def has_private(self):
  192.        return self.key.has_private()
  193.  
  194.    def size(self):
  195.        return self.key.size()
  196.  
  197.    def can_blind(self):
  198.        return False
  199.  
  200.    def can_encrypt(self):
  201.        return False
  202.  
  203.    def can_sign(self):
  204.        return True
  205.  
  206.    def publickey(self):
  207.        return self.implementation.construct((self.key.y, self.key.g, self.key.p, self.key.q))
  208.  
  209.    def __getstate__(self):
  210.        d = {}
  211.        for k in self.keydata:
  212.            try:
  213.                d[k] = getattr(self.key, k)
  214.            except AttributeError:
  215.                pass
  216.        return d
  217.  
  218.    def __setstate__(self, d):
  219.        if not hasattr(self, 'implementation'):
  220.            self.implementation = DSAImplementation()
  221.        t = []
  222.        for k in self.keydata:
  223.            if not d.has_key(k):
  224.                break
  225.            t.append(d[k])
  226.        self.key = self.implementation._math.dsa_construct(*tuple(t))
  227.  
  228.    def __repr__(self):
  229.        attrs = []
  230.        for k in self.keydata:
  231.            if k == 'p':
  232.                attrs.append("p(%d)" % (self.size()+1,))
  233.            elif hasattr(self.key, k):
  234.                attrs.append(k)
  235.        if self.has_private():
  236.            attrs.append("private")
  237.        # PY3K: This is meant to be text, do not change to bytes (data)
  238.        return "<%s @0x%x %s>" % (self.__class__.__name__, id(self), ",".join(attrs))
  239.  
  240. class DSAImplementation(object):
  241.    """
  242.    A DSA key factory.
  243.  
  244.    This class is only internally used to implement the methods of the
  245.    `Crypto.PublicKey.DSA` module.
  246.    """
  247.  
  248.    def __init__(self, **kwargs):
  249.        """Create a new DSA key factory.
  250.  
  251.        :Keywords:
  252.         use_fast_math : bool
  253.                                Specify which mathematic library to use:
  254.  
  255.                                - *None* (default). Use fastest math available.
  256.                                - *True* . Use fast math.
  257.                                - *False* . Use slow math.
  258.         default_randfunc : callable
  259.                                Specify how to collect random data:
  260.  
  261.                                - *None* (default). Use Random.new().read().
  262.                                - not *None* . Use the specified function directly.
  263.        :Raise RuntimeError:
  264.            When **use_fast_math** =True but fast math is not available.
  265.        """
  266.        use_fast_math = kwargs.get('use_fast_math', None)
  267.        if use_fast_math is None:   # Automatic
  268.            if _fastmath is not None:
  269.                self._math = _fastmath
  270.            else:
  271.                self._math = _slowmath
  272.  
  273.        elif use_fast_math:     # Explicitly select fast math
  274.            if _fastmath is not None:
  275.                self._math = _fastmath
  276.            else:
  277.                raise RuntimeError("fast math module not available")
  278.  
  279.        else:   # Explicitly select slow math
  280.            self._math = _slowmath
  281.  
  282.        self.error = self._math.error
  283.  
  284.        # 'default_randfunc' parameter:
  285.        #   None (default) - use Random.new().read
  286.        #   not None       - use the specified function
  287.        self._default_randfunc = kwargs.get('default_randfunc', None)
  288.        self._current_randfunc = None
  289.  
  290.    def _get_randfunc(self, randfunc):
  291.        if randfunc is not None:
  292.            return randfunc
  293.        elif self._current_randfunc is None:
  294.            self._current_randfunc = Random.new().read
  295.        return self._current_randfunc
  296.  
  297.    def generate(self, bits, randfunc=None, progress_func=None):
  298.        """Randomly generate a fresh, new DSA key.
  299.  
  300.        :Parameters:
  301.         bits : int
  302.                            Key length, or size (in bits) of the DSA modulus
  303.                            *p*.
  304.                            It must be a multiple of 64, in the closed
  305.                            interval [512,1024].
  306.         randfunc : callable
  307.                            Random number generation function; it should accept
  308.                            a single integer N and return a string of random data
  309.                            N bytes long.
  310.                            If not specified, a new one will be instantiated
  311.                            from ``Crypto.Random``.
  312.         progress_func : callable
  313.                            Optional function that will be called with a short string
  314.                            containing the key parameter currently being generated;
  315.                            it's useful for interactive applications where a user is
  316.                            waiting for a key to be generated.
  317.  
  318.        :attention: You should always use a cryptographically secure random number generator,
  319.            such as the one defined in the ``Crypto.Random`` module; **don't** just use the
  320.            current time and the ``random`` module.
  321.  
  322.        :Return: A DSA key object (`_DSAobj`).
  323.  
  324.        :Raise ValueError:
  325.            When **bits** is too little, too big, or not a multiple of 64.
  326.        """
  327.  
  328.        # Check against FIPS 186-2, which says that the size of the prime p
  329.        # must be a multiple of 64 bits between 512 and 1024
  330.        for i in (0, 1, 2, 3, 4, 5, 6, 7, 8):
  331.            if bits == 512 + 64*i:
  332.                return self._generate(bits, randfunc, progress_func)
  333.  
  334.        # The March 2006 draft of FIPS 186-3 also allows 2048 and 3072-bit
  335.        # primes, but only with longer q values.  Since the current DSA
  336.        # implementation only supports a 160-bit q, we don't support larger
  337.        # values.
  338.        raise ValueError("Number of bits in p must be a multiple of 64 between 512 and 1024, not %d bits" % (bits,))
  339.  
  340.    def _generate(self, bits, randfunc=None, progress_func=None):
  341.        rf = self._get_randfunc(randfunc)
  342.        obj = _DSA.generate_py(bits, rf, progress_func)    # TODO: Don't use legacy _DSA module
  343.        key = self._math.dsa_construct(obj.y, obj.g, obj.p, obj.q, obj.x)
  344.        return _DSAobj(self, key)
  345.  
  346.    def construct(self, tup):
  347.        """Construct a DSA key from a tuple of valid DSA components.
  348.  
  349.        The modulus *p* must be a prime.
  350.  
  351.        The following equations must apply:
  352.  
  353.        - p-1 = 0 mod q
  354.        - g^x = y mod p
  355.        - 0 < x < q
  356.        - 1 < g < p
  357.  
  358.        :Parameters:
  359.         tup : tuple
  360.                    A tuple of long integers, with 4 or 5 items
  361.                    in the following order:
  362.  
  363.                    1. Public key (*y*).
  364.                    2. Sub-group generator (*g*).
  365.                    3. Modulus, finite field order (*p*).
  366.                    4. Sub-group order (*q*).
  367.                    5. Private key (*x*). Optional.
  368.  
  369.        :Return: A DSA key object (`_DSAobj`).
  370.        """
  371.        key = self._math.dsa_construct(*tup)
  372.        return _DSAobj(self, key)
  373.  
  374. _impl = DSAImplementation()
  375. generate = _impl.generate
  376. construct = _impl.construct
  377. error = _impl.error
  378.  
  379. # vim:set ts=4 sw=4 sts=4 expandtab:
  380.  
Páginas: [1]
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines