예제 #1
0
def channel_zip(input, quant):
    '''
    : channel_zip: 对单个通道着行JPEG压缩
    : param input: 输入图像单通道的矩阵
    : return: tuple=(ac, dc),元组中的两个元素依次为ac编码结果和dc编码结果
    '''
    # 1. 对输入的通道矩阵进行分割,分割为8*8的图像块
    input = mat_divide(input)
    # 2. 依次ac编码每个分割后的8*8矩阵
    row, col = np.shape(input)[0], np.shape(input)[1]
    ac = np.zeros((row, col)).tolist()  # ac系数的编码结果
    dc = []  # 各个8*8子矩阵的dc列表
    for i in range(row):
        for k in range(col):
            # 2.1 对8*8矩阵块作DCT变换,该步骤耗时较久
            sub_input = dct.dct(input[i][k])
            # 2.2 结果再使用输入的量化矩阵进行量化
            sub_input = qua.quantify(sub_input, quant)
            dc.append(int(sub_input[0, 0]))
            # 3.3 量化结果再进行ac编码
            sub_ac = rlc.rlc(sub_input)
            sub_ac = ec.ec_ac(sub_ac)
            ac[i][k] = sub_ac
    # 3. 进行dc编码
    dc = dpcm.dpcm(dc)
    dc = ec.ec_dc(dc)
    return (ac, dc)
예제 #2
0
def list_titles(cfg,
                message_id="12345678901234567",
                device_token="123456789abcdef0123456789abcdef0"):
    soap = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
                   xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                   xmlns:cas="urn:cas.wsapi.broadon.com">
<SOAP-ENV:Body>
<cas:ListTitles xsi:type="cas:ListTitlesRequestType">
  <cas:Version>{cfg.ecdk_version}</cas:Version>
  <cas:MessageId>ECDK-{cfg.device_id}-{message_id}</cas:MessageId>
  <cas:DeviceId>{cfg.device_id}</cas:DeviceId>
  <cas:DeviceToken>WT-{device_token}</cas:DeviceToken>
  <cas:AccountId>{cfg.account_id}</cas:AccountId>
  <cas:ApplicationId>{cfg.application_id}</cas:ApplicationId>
  <cas:TIN>{cfg.tin}</cas:TIN>
  <cas:Region>{cfg.region}</cas:Region>
  <cas:Country>{cfg.country}</cas:Country>
  <cas:Language>{cfg.language}</cas:Language>
  <cas:ListResultOffset>0</cas:ListResultOffset>
  <cas:ListResultLimit>40</cas:ListResultLimit>
  <cas:Attributes>Prices</cas:Attributes>
  <cas:Attributes>MaxUserFileSize</cas:Attributes>
  <cas:Attributes>MaxUserInodes</cas:Attributes>
</cas:ListTitles>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>""".format(cfg=cfg,
                               message_id=message_id,
                               device_token=device_token)
    return EC.send_ecdk("https://cas.shop.wii.com/cas/services/CatalogingSOAP",
                        soap, "urn:cas.wsapi.broadon.com/ListTitles", cfg)
예제 #3
0
파일: ECDSA.py 프로젝트: basilvetas/python
def validate(m, R, Q, n, Elist, char, signature):
	# m, Q, n, Elist, char as above
	# R is d*Q, this is Alice's public key
	# signature is the list [r, s] as above
	r = signature[0]
	s = signature[1]
	z = HashMessage(m, n)
	w = EC.invMod(s, n)
	w = w%n
	u1 = (z*w)%n
	u2 = (r*w)%n
	u1Q = EC.nP(u1, Q, Elist, char)
	u2R = EC.nP(u2, R, Elist, char)
	T = EC.addPts(u1Q, u2R, Elist, char)
	
	return ( (T[0])%n == r%n)
예제 #4
0
def make_users(user_n=5):
    users = []
    for _ in range(user_n):
        prv_key, pub_key = EC.make_key()
        users.append({'prv_key': prv_key, 'pub_key': pub_key})

    return users
예제 #5
0
def check_device_status(cfg,
                        message_id="12345678901234567",
                        device_token="123456789abcdef0123456789abcdef0"):
    soap = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
                   xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                   xmlns:ecs="urn:ecs.wsapi.broadon.com">
<SOAP-ENV:Body>
<ecs:CheckDeviceStatus xsi:type="ecs:CheckDeviceStatusRequestType">
  <ecs:Version>{cfg.ecshop_version}</ecs:Version>
  <ecs:MessageId>ECSHOP-{cfg.device_id}-{message_id}</ecs:MessageId>
  <ecs:DeviceId>{cfg.device_id}</ecs:DeviceId>
  <ecs:DeviceToken>WT-{device_token}</ecs:DeviceToken>
  <ecs:AccountId>{cfg.account_id}</ecs:AccountId>
  <ecs:Region>{cfg.region}</ecs:Region>
  <ecs:Country>{cfg.country}</ecs:Country>
  <ecs:Language>{cfg.language}</ecs:Language>
  <ecs:SerialNo>{cfg.serial_no}</ecs:SerialNo>
</ecs:CheckDeviceStatus>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>""".format(cfg=cfg,
                               message_id=message_id,
                               device_token=device_token)
    return EC.send_ecshop(
        "https://ecs.shop.wii.com/ecs/services/ECommerceSOAP", soap,
        "urn:ecs.wsapi.broadon.com/CheckDeviceStatus", cfg)
예제 #6
0
 def __init__(this):
     this.handshake_done = False
     this.key = None
     this.privkey = randrange(2, EC.order)
     this.pubkey = EC.ec_scalar(EC.E, this.privkey, EC.G)
     this.hash_privkey = hashlib.sha1(str(
         this.privkey).encode("utf-8")).hexdigest()
예제 #7
0
파일: ECDSA.py 프로젝트: basilvetas/python
def sign(m, d, Q, n, Elist, char):
	z = HashMessage(m, n)
	myRand = random.SystemRandom() # a cryptographically secure random number generator
	r = 0
	while(r == 0):
		k = myRand.randint(1, n-1)
		kQ = EC.nP(k, Q, Elist, char)
		r = kQ[0]%n # if r = 0 we will keep looping
		
		# only compute s if r is not zero
		if(r != 0):
			k_inv = EC.invMod(k, n)	
			s = (k_inv*(z + r*d))%n
			if(s == 0): # if s equals 0
				r = 0	# choose a new k and compute r and s again
		
	return [r, s]
예제 #8
0
def verify_transaction(transaction=None):
    if not transaction:
        transaction = input('transaction > ')

    try:
        owner, rec, coin, sig = transaction.split(';')
    except:
        return False

    message = owner + rec + coin
    message = sha256_2(message)
    return EC.verify(owner, sig, message)
예제 #9
0
def purchase_title(title_id,
                   item_id,
                   cfg,
                   message_id="12345678901234567",
                   device_token="Ab3dEF/gHIjKLMnoPqrST"):
    soap = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
                   xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                   xmlns:ecs="urn:ecs.wsapi.broadon.com">
<SOAP-ENV:Body>
<ecs:PurchaseTitle xsi:type="ecs:PurchaseTitleRequestType">
  <ecs:Version>{cfg.ecdk_version}</ecs:Version>
  <ecs:MessageId>ECDK-{cfg.device_id}-{message_id}</ecs:MessageId>
  <ecs:DeviceId>{cfg.device_id}</ecs:DeviceId>
  <ecs:DeviceToken>ST-{device_token}</ecs:DeviceToken>
  <ecs:AccountId>{cfg.account_id}</ecs:AccountId>
  <ecs:ApplicationId>{cfg.application_id}</ecs:ApplicationId>
  <ecs:TIN>{cfg.tin}</ecs:TIN>
  <ecs:Region>{cfg.region}</ecs:Region>
  <ecs:Country>{cfg.country}</ecs:Country>
  <ecs:Language>{cfg.language}</ecs:Language>
  <ecs:SerialNo>{cfg.serial_no}</ecs:SerialNo>
  <ecs:ItemId>{item_id}</ecs:ItemId>
  <ecs:Price>
    <ecs:Amount>0</ecs:Amount>
    <ecs:Currency>POINTS</ecs:Currency>
  </ecs:Price>
  <ecs:Payment>
    <ecs:PaymentMethod>ACCOUNT</ecs:PaymentMethod>
    <ecs:AccountPayment>
      <ecs:AccountNumber>{cfg.account_id}</ecs:AccountNumber>
      <ecs:DeviceToken>{device_token}</ecs:DeviceToken>
    </ecs:AccountPayment>
  </ecs:Payment>
  <ecs:DeviceCert>{cfg.device_cert}</ecs:DeviceCert>
  <ecs:TitleId>{title_id}</ecs:TitleId>
  <ecs:Limits>
    <ecs:Limits>0</ecs:Limits>
    <ecs:LimitKind>PR</ecs:LimitKind>
  </ecs:Limits>
  <ecs:Age>20</ecs:Age>
</ecs:PurchaseTitle>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>""".format(title_id=title_id,
                               item_id=item_id,
                               cfg=cfg,
                               message_id=message_id,
                               device_token=device_token)
    return EC.send_ecdk("https://ecs.shop.wii.com/ecs/services/ECommerceSOAP",
                        soap, "urn:ecs.wsapi.broadon.com/PurchaseTitle", cfg)
예제 #10
0
def detail_test():
    # most modules have their own test
    print("\n Test configuration files")
    conf_test()
    env_test()

    print("\n Test sensors")    
    import BME280
    BME280.test()

    import Turbidity()
    Turbidity.test()

    import EC
    EC.test()

    print("\n High level functions")
    test()

    

    
    
def post_process2(G, P_set, matched, F):

    score = 0
    for (u, v) in matched:
        if u in P_set:
            p = u
            c = v
        else:
            c = u
            p = v
        if (c, p) in F:
            score += float(F[(c, p)])
        else:
            x = 0

    support = []
    att_dic = nx.get_node_attributes(G, 'att')

    for p in list(P_set):
        c_att = att_dic[p]
        neigh_list = G.neighbors(p)
        temp = 0
        for neigh in neigh_list:
            att = att_dic[neigh]
            if att == c_att:
                temp += 1
        support.append(temp)
    '''
    if method ==1:
        ass = nx.attribute_assortativity_coefficient(G, 'att')
        div = ass
    elif method ==2:
        iu = IU.InformationUnfairness(G)
        div = iu
    elif method ==3:
        ec = EC.EchoChamber(G)
        div = ec
    '''

    return round(nx.attribute_assortativity_coefficient(G, 'att'),
                 3), round(IU.InformationUnfairness(G),
                           3), round(EC.EchoChamber(G),
                                     3), round(score,
                                               3), round(st.mean(support), 3)
예제 #12
0
def make_transaction(frm=None, to=None, coin=None, prv_key=None):
    if not (frm and to and coin and prv_key):
        frm = input('pub_key of owner > ')
        to = input('pub_key of receiver > ')
        coin = input('amount of coins > ')
        prv_key = input('prv_key of owner > ')

    if int(coin) <= 0:
        print('amount of coins must be greater that 0')
        import sys
        sys.exit(1)

    message = frm + to + coin
    message = sha256_2(message)

    sig = EC.signiture(prv_key, message)
    sig = sig.decode()

    transaction = f'{frm};{to};{coin};{sig}'
    print('transaction:', transaction)
    return transaction
예제 #13
0
    Created: 10/03/2020
    Last modification: 10/03/2020

    @creator: Corentin J

    Brief: Example file
"""

#-- Import --#
import EC
#- End Import -#

if __name__ == '__main__':
    # Instanciating M-511 curve object
    nM511 = 2**508 + 10724754759635747624044531514068121842070756627434833028965540808827675062043
    CM511 = EC.EllipticCurve("M-511", nM511, 2**511 - 187, [530438, 1, 0])

    # Instantiating generator for the group of points of M-511 curve
    GM511 = EC.Point(
        CM511, 0x5,
        0x2fbdc0ad8530803d28fdbad354bb488d32399ac1cf8f6e01ee3f96389b90c809422b9429e8a43dbf49308ac4455940abe9f1dbca542093a895e30a64af056fa5
    )

    # Instanciating infinite point (zero element for +)
    Z = EC.Point(CM511)
    print(Z + GM511 == GM511)

    # Testing efficiency of multiplication by large integers
    n = 654656845357984954675767598651271325802657127103756757421371765121076751076571757257965331197796511321646517
    P = n * GM511
    Q = P - GM511
예제 #14
0
    if (actual == from_message):
        return True
    else:
        print(
            "ERROR: Out of order message! Could be an attacker message! (Expected %d, got %d)"
            % (actual, from_message))
        return False


hostA = Host("hostA")
hostB = Host("hostB")

# Assume that both host's already know each others public ECDSA keys
# Their public ECDSA keys are "common knowledge", like CA certificates in a browser
print("Host A generating ECDSA keys...")
EC.generate_ECDSA_keys(hostA.name)
print("\nHost B generating ECDSA keys...")
EC.generate_ECDSA_keys(hostB.name)

print("\n***STARTING LOCAL TRANSMISSION***\n")

print("Host A generating ECDHE keys...")
hostA.private_key_ECDHE, hostA.public_key_ECDHE, hostA.prime_ECDHE, hostA.a_ECDHE = EC.gen_ECDHE_keys(
    "hostA")
print("\nHost B generating ECDHE keys...")
hostB.private_key_ECDHE, hostB.public_key_ECDHE, hostB.prime_ECDHE, hostB.a_ECDHE = EC.gen_ECDHE_keys(
    "hostB")

print(
    "\nHost A signing its ECDHE public key and sequence number with its ECDSA private key..."
)
예제 #15
0
                print(e.args[0] + ": JSON Error - quitting")
                exit()

            try:
                if ('x' not in spub.keys()) or ('y' not in spub.keys()):
                    print("ERROR: need x,y keys in json")
                    exit()
            except Exception as e:
                print(e.args[0] + ": JSON Error II - quitting")
                exit()

            if (type(spub['x']) != int) or (type(spub['y']) != int):
                print("ERROR: x and y should be ints")
                exit()

            spub_point = EC.ec_point(EC.E, spub['x'], spub['y'])
            shared_point = EC.ec_scalar(EC.E, S.privkey, spub_point)

            S.key = kdf(shared_point)
            S.handshake_done = True

            continue

        #Get Super Cool Fact!
        if cmd == "2":
            if S.handshake_done == False:
                print("Need to perform handshake first!")
                continue

            cf = choice(cool_facts)
예제 #16
0
    <ecs:Currency>POINTS</ecs:Currency>
  </ecs:Price>
  <ecs:Discount>0</ecs:Discount>
  <ecs:Payment>
    <ecs:PaymentMethod>ACCOUNT</ecs:PaymentMethod>
    <ecs:AccountPayment>
      <ecs:AccountNumber>{cfg.account_id}</ecs:AccountNumber>
      <ecs:DeviceToken>{device_token}</ecs:DeviceToken>
    </ecs:AccountPayment>
  </ecs:Payment>
  <ecs:DeviceCert>{cfg.device_cert}</ecs:DeviceCert>
  <ecs:TitleId>{title_id}</ecs:TitleId>
  <ecs:Limits>
    <ecs:Limits>0</ecs:Limits>
    <ecs:LimitKind>PR</ecs:LimitKind>
  </ecs:Limits>
</ecs:PurchaseTitle>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>""".format(title_id=title_id,
                               item_id=item_id,
                               cfg=cfg,
                               message_id=message_id,
                               device_token=device_token)
    return EC.send_ecshop(
        "https://ecs.shop.wii.com/ecs/services/ECommerceSOAP", soap,
        "urn:ecs.wsapi.broadon.com/PurchaseTitle", cfg)


if __name__ == "__main__":
    cfg = EC.Config("ec.cfg")
예제 #17
0
import sys
import EC
from PyQt5.QtWidgets import QApplication, QMainWindow

if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainWindow = QMainWindow()
    ui = EC.Ui_MainWindow()
    ui.setupUi(mainWindow)
    mainWindow.show()
    sys.exit(app.exec_())
예제 #18
0
from nltk.corpus import comtrans
import A
import B
import EC

if __name__ == '__main__':
    aligned_sents = comtrans.aligned_sents()[:350]
    A.main(aligned_sents)
    B.main(aligned_sents)
    EC.main(aligned_sents)
예제 #19
0
    @creator: Corentin J

    Brief: Some Montgomery and Weierstrass Elliptic Curves parameters
"""

#-- Import --#
import EC
#- End Import -#

# ------------------------------------------------------- #
# Montgomery curves : y^2 = x^3 + a.x^2 + b.x + c (mod p) #
# ------------------------------------------------------- #
""" M-511 curve : 2013 Aranha–Barreto–Pereira–Ricardini (formerly named Curve511187) """
nM511 = 2**508 + 10724754759635747624044531514068121842070756627434833028965540808827675062043
CM511 = EC.EllipticCurve("M-511", nM511, 2**511 - 187, [530438, 1, 0])
GM511 = EC.Point(
    CM511, 0x5,
    0x2fbdc0ad8530803d28fdbad354bb488d32399ac1cf8f6e01ee3f96389b90c809422b9429e8a43dbf49308ac4455940abe9f1dbca542093a895e30a64af056fa5
)
""" Curve383187 : 2013 Aranha–Barreto–Pereira–Ricardini; authors subsequently recommended switching to M-383 """
n383187 = 2**380 + 356080847217269887368687156533236720299699248977882517025
C383187 = EC.EllipticCurve("Curve 383187", n383187, 2**383 - 187,
                           [229969, 1, 0])
G383187 = EC.Point(
    C383187, 0x5,
    0x1eebe07dc1871896732b12d5504a32370471965c7a11f2c89865f855ab3cbd7c224e3620c31af3370788457dd5ce46df
)
""" M-383 : 2013 Aranha–Barreto–Pereira–Ricardini """
nM383 = 2**380 + 166236275931373516105219794935542153308039234455761613271
CM383 = EC.EllipticCurve("M-383", nM383, 2**383 - 187, [2065150, 1, 0])