コード例 #1
0
ファイル: elgamaltest.py プロジェクト: mar-v-in/joeecc
def elgamal_encrypt(recipient_pubkey, msg, msg_width_bits):
    k = ECPrivateKey.generate(curve)
    C1 = k.pubkey.point
    C2 = k.scalar * recipient_pubkey.point
    P_m = msg_to_point(curve, msg, msg_width_bits=msg_width_bits)
    ciphertext = (C1, C2 + P_m)
    return ciphertext
コード例 #2
0
ファイル: ecctest.py プロジェクト: mdxs/joeecc
from ecc import AffineCurvePoint, ShortWeierstrassCurve, getcurvebyname
from ecc import ECPrivateKey

def separator():
	print("-" * 150)


usedcurve = getcurvebyname("secp112r1")
#usedcurve = getcurvebyname("brainpoolP160r1")
#usedcurve = getcurvebyname("secp192k1")
print("Selected curve parameters:")
print(str(usedcurve))
separator()

privatekey = ECPrivateKey(0x12345, usedcurve)
print("Generated privatekey")
print(str(privatekey))
separator()


########################### Encryption example ###########################
e = privatekey.pubkey.ecies_encrypt()
print("Encryption")
print("Transmitted R  :", e["R"])
print("Symmetric key S:", e["S"])
separator()

# And decrypt at receiver
print("Decryption")
recovered_s = privatekey.ecies_decrypt(e["R"])
コード例 #3
0
ファイル: ed25519test.py プロジェクト: ash2005/joeecc
#	You should have received a copy of the GNU General Public License
#	along with joeecc; if not, write to the Free Software
#	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#	Johannes Bauer <*****@*****.**>
#

import time
import sys
from ecc import getcurvebyname, ECPrivateKey
from StopWatch import StopWatch

curve = getcurvebyname("ed25519")

if len(sys.argv) < 2:
	keypair = ECPrivateKey.eddsa_generate(curve)
	print("Generating keypair on the fly")
else:
	keypair = ECPrivateKey.loadkeypair(bytes.fromhex(sys.argv[1]))
print("Keypair:", keypair)

msg = b"Foobar!"
print("Message:", msg)

signature = keypair.eddsa_sign(msg)
print("Signature:", signature)

print("Verify correct message: %s (should be True)" % (keypair.pubkey.eddsa_verify(msg, signature)))
print("Verify forged message : %s (should be False)" % (keypair.pubkey.eddsa_verify(msg + b"x", signature)))

コード例 #4
0
ファイル: elgamaltest.py プロジェクト: mar-v-in/joeecc
    k = ECPrivateKey.generate(curve)
    C1 = k.pubkey.point
    C2 = k.scalar * recipient_pubkey.point
    P_m = msg_to_point(curve, msg, msg_width_bits=msg_width_bits)
    ciphertext = (C1, C2 + P_m)
    return ciphertext


def elgamal_decrypt(recipient_privkey, ciphertext, msg_width_bits):
    (C1, C2) = ciphertext
    Cp = C1 * recipient_privkey.scalar
    P_m = C2 + (-Cp)
    int_message = int(P_m.x) & ((1 << msg_width_bits) - 1)
    msg = int.to_bytes(int_message,
                       byteorder="little",
                       length=(msg_width_bits + 7) // 8)
    return msg


privkey = ECPrivateKey.generate(curve)
pubkey = privkey.pubkey

message = b"foobar"
print("Message:", message)
ciphertext = elgamal_encrypt(pubkey, message, msg_width_bits=256)
print("Ciphertext:")
print("    C1 =", ciphertext[0])
print("    C2 =", ciphertext[1])
plaintext = elgamal_decrypt(privkey, ciphertext, msg_width_bits=256)
print("Plaintext:", plaintext)
コード例 #5
0
ファイル: ecctest.py プロジェクト: yangpengtaow/joeecc
from ecc import AffineCurvePoint, ShortWeierstrassCurve, getcurvebyname
from ecc import ECPrivateKey

def separator():
	print("-" * 150)


usedcurve = getcurvebyname("secp112r1")
#usedcurve = getcurvebyname("brainpoolP160r1")
#usedcurve = getcurvebyname("secp192k1")
print("Selected curve parameters:")
print(str(usedcurve))
separator()

privatekey = ECPrivateKey(0x12345, usedcurve)
print("Generated privatekey")
print(str(privatekey))
separator()


########################### Encryption example ###########################
e = privatekey.pubkey.ecies_encrypt()
print("Encryption")
print("Transmitted R  :", e["R"])
print("Symmetric key S:", e["S"])
separator()

# And decrypt at receiver
print("Decryption")
recovered_s = privatekey.ecies_decrypt(e["R"])
コード例 #6
0
#	You should have received a copy of the GNU General Public License
#	along with joeecc; if not, write to the Free Software
#	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#	Johannes Bauer <*****@*****.**>
#

import time
import sys
from ecc import getcurvebyname, ECPrivateKey
from StopWatch import StopWatch

curve = getcurvebyname("ed25519")

if len(sys.argv) < 2:
    keypair = ECPrivateKey.eddsa_generate(curve)
    print("Generating keypair on the fly")
else:
    keypair = ECPrivateKey.loadkeypair(bytes.fromhex(sys.argv[1]))
print("Keypair:", keypair)

msg = b"Foobar!"
print("Message:", msg)

signature = keypair.eddsa_sign(msg)
print("Signature:", signature)

print("Verify correct message: %s (should be True)" %
      (keypair.pubkey.eddsa_verify(msg, signature)))
print("Verify forged message : %s (should be False)" %
      (keypair.pubkey.eddsa_verify(msg + b"x", signature)))
コード例 #7
0
ファイル: ecccc.py プロジェクト: ncme/ecccc
def print_domainparams(curve, f):
    print(arg.comment_symbol + str(curve))
    params = curve.domainparams

    print(arg.comment_symbol + "Relevant domain parameters:")
    if curve.curvetype == "shortweierstrass":
        print_code("a", f(params.a), comment="curve parameter a_4 = a")
        print_code("minus_a", f(-params.a), comment="-a mod p")
        print_code("b", f(params.b), comment="curve parameter a_6 = b")
    if curve.curvetype == "montgomery":
        print_code("A", f(params.a))
        print_code("B", f(params.b))
        print_code("2A",
                   f(params.a * 2),
                   comment="used in Okeya and Sakurai y-coord recovery")
        print_code("2B",
                   f(params.b * 2),
                   comment="used in Okeya and Sakurai y-coord recovery")
    if curve.curvetype == "twistededwards":
        print_code("a", f(params.a), comment="curve twist")
        print_code("d", f(params.d))

    print_code("p", f(params.p), comment="the modulus")
    print_code("n", f(params.n), comment="the group order")
    if curve.curvetype == "shortweierstrass":
        print_code("h", f(params.h), comment="the cofactor")
    print_code("G_x",
               f(params.G.x),
               comment="the x coordinate of the base point")
    print_code("G_y",
               f(params.G.y),
               comment="the y coordinate of the base point")

    print(arg.comment_symbol + "Prominent field elements:")
    print_code("zero", f(FieldElement(0, params.p)))
    print_code("one", f(FieldElement(1, params.p)))
    print_code("minus_one", f(FieldElement(-1, params.p)))

    print(arg.comment_symbol + "Constants for group operations:")
    print_code(
        "p_r",
        f(params.p
          ^ 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe
          ),
        comment="2^256 - p",
    )
    print_code(
        "pr_squared",
        f(
            FieldElement(
                params.p ^
                0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe,
                params.p,
            ).sqr()),
        comment="(2^256 - p)^2",
    )
    print_code(
        "n_r",
        f(params.n
          ^ 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe
          ),
        comment="order-n xor 2^(bits)-1",
    )
    print_code(
        "mu_n",
        f(calculate_barrett_constant(params.n),
          words=int((256 + arg.word_size) / arg.word_size)),
        words=int(288 / arg.word_size),
        comment="constant μ for reducing n with Barett modular reduction",
    )
    print_code(
        "mu_p",
        f(calculate_barrett_constant(params.p),
          words=int((256 + arg.word_size) / arg.word_size)),
        words=int(288 / arg.word_size),
        comment="constant μ for reducing p with Barett modular reduction",
    )
    print_code(
        "mp_inv",
        f((-FieldElement(params.p, 2**16)).inverse(),
          words=int(ceil(16 / arg.word_size))),
        comment="inverse of -(p mod 2^16)",
    )

    print(arg.comment_symbol + "Constants for conversions:")
    print_code("delta", f(delta), comment="(p+A)/3")
    print_code("c", f(c), comment="sqrt(-(A+2)")
    print_code("c_inv",
               f(FieldElement(c, wei.domainparams.p).inverse()),
               comment="inverse of c")

    if arg.test:
        print(arg.comment_symbol + "Random test vectors:")
        if curve.curvetype == "shortweierstrass":
            p = curve.getpointwithx(
                0xde2444bebc8d36e682edd27e0f271508617519b3221a8fa0b77cab3989da97c9
            )
            if not p:
                p = curve.getpointwithx(
                    0xee2444bebc8d36e682edd27e0f271508617519b3221a8fa0b77cab3989da97c9
                )
            if p:
                s1, s2 = p
            else:
                s1 = generate_random_point(curve)
            print_code("Sx", f(s1.x))
            print_code("Sy", f(s1.y))
            p = curve.getpointwithx(
                0x55a8b00f8da1d44e62f6b3b25316212e39540dc861c89575bb8cf92e35e0986b
            )
            if not p:
                p = curve.getpointwithx(
                    0x45a8b00f8da1d44e62f6b3b25316212e39540dc861c89575bb8cf92e35e0986b
                )
            if p:
                t1, t2 = p
            else:
                t1 = generate_random_point(curve)
            print_code("Tx", f(t1.x))
            print_code("Ty", f(t1.y))
            secret = 0xc51e4753afdec1e6b6c6a5b992f43f8dd0c7a8933072708b6522468b2ffb06fd
            print_code("Sec", f(secret))
            a1 = curve.point_addition(s1, t1)
            assert a1.oncurve()
            print_code("AddX", f(a1.x))
            print_code("AddY", f(a1.y))
            m1 = secret * s1
            assert m1.oncurve()
            print_code("MulX", f(m1.x))
            print_code("MulY", f(m1.y))
            d1 = s1 + s1
            assert d1.oncurve()
            print_code("DubX", f(d1.x))
            print_code("DubY", f(d1.y))
            d2 = t1 + t1
            assert d2.oncurve()
            print_code("DubTX", f(d2.x))
            print_code("DubTY", f(d2.y))
            print(arg.comment_symbol +
                  "Constants for testing field operations")
            print_code(
                "Full",
                f(
                    FieldElement(
                        0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff,
                        params.p,
                    )),
            )
            print_code("One", f(FieldElement(0x01, params.p)))
            print_code(
                "resultFullAdd",
                f(
                    FieldElement(
                        0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff,
                        params.p,
                    ) + FieldElement(0x01, params.p)),
            )
            print_code(
                "primeMinusOne",
                f(
                    FieldElement(params.p, params.p) -
                    FieldElement(0x01, params.p)),
            )
            print_code("inv", f(FieldElement(2, params.p).inverse()))
            print_code(
                "one",
                f(FieldElement(2, params.p) // FieldElement(2, params.p)))
            print_code(
                "resultDoubleMod",
                f(2 * (FieldElement(params.p, params.p) -
                       FieldElement(0x01, params.p))),
            )
            print_code(
                "resultQuadMod",
                f(
                    FieldElement(
                        (FieldElement(params.p, params.p) -
                         FieldElement(0x01, params.p)).__int__(),
                        params.p**2,
                    )**2,
                    words=int(512 / arg.word_size),
                ),
                words=int(512 / arg.word_size),
            )
            print_code(
                "resultFullMod",
                f(
                    FieldElement(params.p, params.p) *
                    FieldElement(params.p, params.p)),
            )
            print_code(
                "orderMinusOne",
                f(
                    FieldElement(params.n, params.p) -
                    FieldElement(0x01, params.p)),
            )
            print_code(
                "orderResultDoubleMod",
                f(2 * FieldElement(
                    (FieldElement(params.n, params.p) -
                     FieldElement(0x01, params.p)).sigint(),
                    params.n,
                )),
            )
        ecdsaTestMessage = (
            0x48616C6C6F2C205468697320697320612068617368206F662061207365637572)
        if ecdsaTestMessage >= params.n:
            ecdsaTestMessage = (
                0x08616C6C6F2C205468697320697320612068617368206F662061207365637572
            )
        ecdsaTestSecret = (
            0x41C1CB6B51247A144321435B7A80E714896A33BBAD7294CA401455A194A949FA)
        if ecdsaTestSecret >= params.n:
            ecdsaTestSecret = (
                0x01C1CB6B51247A144321435B7A80E714896A33BBAD7294CA401455A194A949FA
            )
        ecdsaTestRand1 = (
            0x0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F20)
        ecdsaTestRand2 = (
            0x01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
        msg = ecdsaTestMessage.to_bytes(32, byteorder=arg.byte_order)
        print_code("ecdsaTestMessage", f(ecdsaTestMessage))
        print_code("ecdsaTestSecret", f(ecdsaTestSecret))
        assert ecdsaTestSecret < params.n
        assert ecdsaTestMessage < params.n
        assert ecdsaTestRand1 < params.n
        assert ecdsaTestRand2 < params.n
        assert ecdsaTestSecret > 0
        assert ecdsaTestMessage > 0
        assert ecdsaTestRand1 > 0
        assert ecdsaTestRand2 > 0
        p1 = ecdsaTestSecret * params.G
        print_code("ecdsaTestRand1", f(ecdsaTestRand1))
        print_code("ecdsaTestRand2", f(ecdsaTestRand2))
        print_code("p1x", f(p1.x))
        print_code("p1y", f(p1.y))
        pk = ECPrivateKey(ecdsaTestSecret, curve)
        assert pk.scalar < params.n - 1
        assert pk.scalar > 0
        res1 = pk.ecdsa_sign_hash(msg, k=ecdsaTestRand1)
        print_code("ecdsaTestresultR1", f(res1.r))
        print_code("ecdsaTestresultS1", f(res1.s))
        res2 = pk.ecdsa_sign_hash(msg, k=ecdsaTestRand2)
        print_code("ecdsaTestresultR2", f(res2.r))
        print_code("ecdsaTestresultS2", f(res2.s))
        verify_original = pk.pubkey.ecdsa_verify_hash(msg, res1)
        verify_modified = pk.pubkey.ecdsa_verify_hash(msg, res2)
        assert verify_original
        assert verify_modified