---
tags: 普鴻資訊
---
<style>
html, body, .ui-content {
background-color: #333;
color: #ddd;
}
</style>
# 普鴻資訊暑期實習 Notes
<center>MADE BY 方雍憲</center>
---
### 密碼學相關統整地圖 Cryptography 2021-07-26 更
![](https://i.imgur.com/iDZQYTe.jpg)
---
### 加解密實作 2021-07-19 (Using Python.)
AES
----
from base64 import b64encode, b64decode
import hashlib
from Cryptodome.Cipher import AES
import os
from Cryptodome.Random import get_random_bytes
def encrypt (plain_text, password) :
# generate a random salt
salt = get_random_bytes(AES.block_size)
# use the Scrypt KDF to get a private key from the password
private_key = hashlib.scrypt(
password.encode(), salt=salt, n= 2 ** 14 , r= 8 , p= 1 , dklen= 32 )
# create cipher config
cipher_config = AES.new(private_key, AES.MODE_GCM)
# return a dictionary with the encrypted text
cipher_text, tag = cipher_config.encrypt_and_digest(bytes(plain_text, 'utf-8' ))
return {
'cipher_text' : b64encode(cipher_text).decode( 'utf-8' ),
'salt' : b64encode(salt).decode( 'utf-8' ),
'nonce' : b64encode(cipher_config.nonce).decode( 'utf-8' ),
'tag' : b64encode(tag).decode( 'utf-8' )
}
def decrypt (enc_dict, password) :
# decode the dictionary entries from base64
salt = b64decode(enc_dict[ 'salt' ])
cipher_text = b64decode(enc_dict[ 'cipher_text' ])
nonce = b64decode(enc_dict[ 'nonce' ])
tag = b64decode(enc_dict[ 'tag' ])
# generate the private key from the password and salt
private_key = hashlib.scrypt(
password.encode(), salt=salt, n= 2 ** 14 , r= 8 , p= 1 , dklen= 32 )
# create the cipher config
cipher = AES.new(private_key, AES.MODE_GCM, nonce=nonce)
# decrypt the cipher text
decrypted = cipher.decrypt_and_verify(cipher_text, tag)
return decrypted
def main () :
password = input( "Password: " )
# First let us encrypt secret message
encrypted = encrypt( "The secretest message here" , password)
print(encrypted)
# Let us decrypt using our original password
decrypted = decrypt(encrypted, password)
print(bytes.decode(decrypted))
main()
---
## S-DES
FIXED_IP = [2, 6, 3, 1, 4, 8, 5, 7]
FIXED_EP = [4, 1, 2, 3, 2, 3, 4, 1]
FIXED_IP_INVERSE = [4, 1, 3, 5, 7, 2, 8, 6]
FIXED_P10 = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
FIXED_P8 = [6, 3, 7, 4, 8, 5, 10, 9]
FIXED_P4 = [2, 4, 3, 1]
S0 = [[1, 0, 3, 2],
[3, 2, 1, 0],
[0, 2, 1, 3],
[3, 1, 3, 2]]
S1 = [[0, 1, 2, 3],
[2, 0, 1, 3],
[3, 0, 1, 0],
[2, 1, 0, 3]]
KEY = ''
def permutate(original, fixed_key):
new = ''
for i in fixed_key:
new += original[i - 1]
return new
def left_half(bits):
return bits[:int(len(bits)/2)]
def right_half(bits):
return bits[int(len(bits)/2):]
def shift(bits):
rotated_left_half = left_half(bits)[1:] + left_half(bits)[0]
rotated_right_half = right_half(bits)[1:] + right_half(bits)[0]
return rotated_left_half + rotated_right_half
def key1():
return permutate(shift(permutate(KEY, FIXED_P10)), FIXED_P8)
def key2():
return permutate(shift(shift(shift(permutate(KEY, FIXED_P10)))), FIXED_P8)
def xor(bits, key):
new = ''
for bit, key_bit in zip(bits, key):
new += str(((int(bit) + int(key_bit)) % 2))
return new
def lookup_in_sbox(bits, sbox):
row = int(bits[0] + bits[3], 2)
col = int(bits[1] + bits[2], 2)
return '{0:02b}'.format(sbox[row][col])
def f_k(bits, key):
L = left_half(bits)
R = right_half(bits)
bits = permutate(R, FIXED_EP)
bits = xor(bits, key)
bits = lookup_in_sbox(left_half(bits), S0) + lookup_in_sbox(right_half(bits), S1)
bits = permutate(bits, FIXED_P4)
return xor(bits, L)
def encrypt(plain_text):
bits = permutate(plain_text, FIXED_IP)
temp = f_k(bits, key1())
bits = right_half(bits) + temp
bits = f_k(bits, key2())
print('The encryption result is = ' + permutate(bits + temp, FIXED_IP_INVERSE))
def decrypt(cipher_text):
bits = permutate(cipher_text, FIXED_IP)
temp = f_k(bits, key2())
bits = right_half(bits) + temp
bits = f_k(bits, key1())
print('The decryption result is = ' + permutate(bits + temp, FIXED_IP_INVERSE))
if __name__ == '__main__':
oper = input('Enter D for encryption and E for decryption:')
KEY = input('Enter the 10-digit key:')
if oper == 'D':
msg = input('Enter 8-digit plaintext:')
encrypt(msg)
elif oper == 'E':
msg = input('Enter 8-digit ciphertext:')
decrypt(msg)
input('--- Type enter to end the process ---')
---
## RSA
from pprint import pprint
from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64
def get_key():
rsa = RSA.generate(1024, Random.new().read)
private_pem = rsa.exportKey()
public_pem = rsa.publickey().exportKey()
return {
"public_key": public_pem.decode(),
"private_key": private_pem.decode()
}
from pprint import pprint
from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64
def get_key():
rsa = RSA.generate(1024, Random.new().read)
private_pem = rsa.exportKey()
public_pem = rsa.publickey().exportKey()
return {
"public_key": public_pem.decode(),
"private_key": private_pem.decode()
}
private_key = """-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDfEQ82qUrto7h4BL3TsA/DFXSdM44cbeY4kPccD7gLGhaZRClz
YKIh5zYdfjBGF+0HXfMa1u9b7GNs2AjVIsx8Kx0QLnMfmtkmGWGhOXz/9IDLKJOx
0weKv61gysKItgzVKn2mbLool4R/PQBc3AjDyHw+io1KpVz+3kRTaGs1fQIDAQAB
AoGAWB4kFWLA/6k6OOcemd4mC9mQ7HyuOdrMJDJX+5TWDkSrArajbTmSMrRkczgj
F71h3BQn8cVQXs695ARfUNrjTbi2Y0LjN7ScK7ExzTLdoMEFw5JsHggJZ0zBQY6w
mwOdGfqzA6tZPXgkn+jqEha+CD6GrwnTM1oDGJC/aKG2OmECQQDkO9IhUhFc/PSU
0zvGE6AOcqk5wlOuvMg+oAFHJHJZ9XW7+X/Nx0ZoVDFq/cZQj+46t+fiwUwhdW7l
IfCvNGKFAkEA+jRQmWGKrbf1ns4S0SezJvysd5O6otRGJXr+Ex2uDhc39ZTeUsyg
kjrLhp8STLMOmql+8g5fghct17EuCX1EmQJBAJz9BNnEkIrst/OSpH/nyeWGOx6u
q077LaXd+2MLD9kO/O/Se3V5B9YFa4STkJCjoBMloswXd51gIGpdgSeSmd0CQQCL
PrwwcGmWfo+ynqs4PajlpK9zKQMwhYS4bTejedwZOXDKOtx0Ji+i0hfcxwCPMQOK
rZPZsIgUxUOdC508aLvZAkBDkHxunCzDm0w4DdTUN7S9YSpVvQEjK/xUQiWaKV12
8QgskhU2DNdYK2NxifnWrKtx3uQmqMxX5aLuJZ4493yr
-----END RSA PRIVATE KEY-----"""
public_key = """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfEQ82qUrto7h4BL3TsA/DFXSd
M44cbeY4kPccD7gLGhaZRClzYKIh5zYdfjBGF+0HXfMa1u9b7GNs2AjVIsx8Kx0Q
LnMfmtkmGWGhOXz/9IDLKJOx0weKv61gysKItgzVKn2mbLool4R/PQBc3AjDyHw+
io1KpVz+3kRTaGs1fQIDAQAB
-----END PUBLIC KEY-----
"""
def rsa_encode(message, public_key):
rsakey = RSA.importKey(public_key)
cipher = PKCS1_v1_5.new(rsakey)
cipher_text = base64.b64encode(
cipher.encrypt(message.encode(encoding="utf-8")))
return cipher_text.decode()
def rsa_decode(cipher_text, private_key):
rsakey = RSA.importKey(private_key)
cipher = PKCS1_v1_5.new(rsakey)
text = cipher.decrypt(base64.b64decode(cipher_text), "ERROR")
return text.decode()
if __name__ == '__main__':
message = "rsa test sammy!"
cipher = rsa_encode(message, public_key)
print(cipher)
msg = rsa_decode(cipher, private_key)
print(msg)
---
## SVN Branch Rename Impact Confirm 2021-07-27
SVN conflict:
#### WHY?(原因)
1.USER1&USER2:Access the same file at the same time
2.Both of them modify the same file separately
3.USER1:Upload modified version
4.USER2:Out-Of-Date error occurred during upload
#### Solutions(解決方式,以下說明):
##### 1.Lock-Modify-Unlock
##### 2.Copy-Modify-Merge
##### Copy-Modify-Merge is better than Lock-Modify-Unlock,
Since:
1.Will not cause management problems
Copy-modify-merge does not require locking steps,Therefore, unlike the Lock-Modify-Unlock model, the lock will be forgotten and cause no problems with access to archives.
2.Will not cause unnecessary waste of time.
When different users want to access the same file,Copy-Modify-Merge allows users to access at the same time, while progressing on their own work copy
Modify the action, so for the user, it will not be because this is a shared file.
##### Tree Conflict:
When a user moves/deletes/renames a file or folder, and another user also moves/deletes/renames/modifies that file or folder, a tree conflict may occur.
#### Solutions:
Decide on the merge method and version after saving(SVN trunk branch to trunk).
Reference:
https://chainding.wordpress.com/2010/01/08/branch-by-abstraction/
https://docs.wandisco.com/svn/archive/ms-plus1.3/appendix.html
https://blog.miniasp.com/post/2010/01/28/Subversion-Branches-and-Merging-using-TortoiseSVN
https://www.cnblogs.com/shawWey/p/12029399.html
---
### SECUR TEST TOOL (promvlt)
2021 07 28
Test Data -> Using Variant LMK tool進行運算,得Encrypted value。
同時使用 OpenCryptoTest進行DES運算並與test log進行比對。
此外也須同使檢查與確認。
Task:
參考 OpenCrypto TEST開發TOOL,Reference to Variant LMK Tool.
---
## 前端GUI (Python)
Demo:
![](https://i.imgur.com/7bXGrfX.jpg)
頁面布局:
測試訊息處預計作為顯示文字處,右側下方設計為工具按鈕;最左側大半部做為input、output 加解密的輸入與顯示視窗格位。
reference:https://tkdocs.com/tutorial/index.html
---
### 透過GUI進行參數傳遞並完成DES-ECB加密(.py return to script)
#### Result:
![](https://i.imgur.com/Kq0sPcn.jpg)
回傳於output格位,DES-ECB 加密ok!
![](https://i.imgur.com/gqx1RmP.jpg)
DES:
```
import pyDes
import binascii
class Descryption:
def des_encrypt(self, key, plaintext):
iv = secret_key = key
k = pyDes.des(secret_key, pyDes.CBC, iv, pad=None, padmode = pyDes.PAD_PKCS5)
data = k.encrypt(plaintext, padmode=pyDes.PAD_PKCS5)
print(binascii.b2a_hex(data).decode())
def des_decrypt(self, key, ciphertext):
iv = secret_key = key
k = pyDes.des(secret_key, pyDes.CBC, iv, pad=None, padmode = pyDes.PAD_PKCS5)
data = k.decrypt(binascii.a2b_hex(ciphertext), padmode=pyDes.PAD_PKCS5)
print(data.decode())
des = Descryption()
while True:
key = input("KEY:\n")
mode = input("encrypt or decrypt?:\n")
if mode.strip() == 'e':
plaintext = input("plaintext:\n")
des.des_encrypt(key, plaintext.strip())
elif mode.stript() == 'd':
ciphertext = input("ciphertext:\n")
des.des_decrypt(key, ciphertext.strip())
##Sammy fang 07-30
```
完成DES ECB功能-初版
![](https://i.imgur.com/4CdG70Y.jpg)
完成GUI與演算法功能-一版
![](https://i.imgur.com/JpG8Z3a.jpg)
完成新版GUI與工具整合-二版
![](https://i.imgur.com/Jfw95UH.jpg)
---
## BP-Tool
BP-Tool是 EFTlab 公司開發的主要面向金融和智慧卡的數據加解密,數據轉換工具,
金融領域常用算法如AES RSA DES 都能計算,還能計算DUKPT AES/DES, 以及TR31 KBH的格式解析和數據計算,另外還能提供EMV ATR parser(ATR命令解析),HSM加密機指令組包,Sim Card文件編輯和解析。
EFT-POS,MPOS , SCR 等產品都要過PCI 和UPTS ,EMV認證,這些都離不開加密工具的幫助。SERD OP等認證需要也離不開RSA和認證與解析,該工具都能幫上忙。
The BP-Tools set consist from applications supporting EFT testing, benchmarking and transaction service development. BP-Tools suite currently consists of following three components:
- BP-CCALC: Cryptographic Calculator
- BP-CardEdit: Thales P3 Input/Output file editor
- BP-EMVT: EMV Tool
- BP-HCMD: Thales HSM Commander
Features
* AES (Advanced Encryption Standard) cipher operations with ECB, CBC, CFB, OFB modes
* ANSI 9.19 (ISO/IEC 9797-1, algorithm 3)
* Asymmetric cryptography (RSA) - certificate generation, encryption, decryption, signing and validation
* DES/3DES cipher operations with ECB, CBC, CFB-8, OFB-8, OFB-64 modes
* Hashing (MD4, MD5, SHA-1, SHA-256, SHA-384, SHA-512)
* DUKPT AES/DES Calc
* TR31 Key Parser
* Strong and secure key generation (64/128/192 bit)
* Key components combination
* Key parity check (odd, even)
* Key checksum generation
* LUHN digit check & generation
* Character set conversion (ASCII, EBCDIC, binary, hexadecimal)
* Thales keys calculator
* Thales LMK key lookup
* Payments: AS2805 cryptography
* Payments: CVV, CVV2 and iCVV generation
* Payments: IPEK and PEK derivation (DUKPT)
* Payments: MAC encryption (DUKPT and ANSI X9.9)
* Payments: PIN block generation and decoding
* Payments: PIN encryption and decoding (DUKPT, ZKA)
* Payments: Zentraler Kreditausschuss / ZKA key derivation and PIN block encryption
* EMV: AAC, ARCQ, TC & ARCP calculation
* EMV: APDU response parser
* EMV: Session key & UDK derivation
* EMV: Static Data Authentication (SDA) option
* EMV: TLV & bit flags parser
* EMV: Parser support for a range of PayPass tags
* Multi-platform support (Microsoft, Ubuntu Linux)
* PIN offset Derivation (IBM 3624 PIN Generation Algorithm)
* Answer To Reset (ATR) parser for SmartCards
---
## cmd_test
PATH: /home/m10k_ship_test_v1.0.0/bin/cmd_test
![](https://i.imgur.com/T8nOfrQ.png)
> * -a 192.168.0.143 為執行中的機器IP address
> 127.0.0.1 為local host address
>
> * -p 3500 為HSM port 接口
> 如何啟動HSM simulator
>
> * -h 4: 為message header length,default為4
>
> * -m 3: 為M-series(ex: M5000, M10K)
指令範例:./cmd_test -a 127.0.0.1 -p 3501 -h 4 -m 3 -d 0 -f /file/path
(ex: ./…/repo/m10k/def/fisc_atm/SC_001)
---
## Run_case
PATH: /home/m10k_ship_test_v1.0.0/bin/run_case
![](https://i.imgur.com/cfYtJUT.png)
## Test case
[Redmine #2318(Ex)](https://59.124.127.62:2999/redmine/issues/2318)
[Redmine #2318(In)](https://192.168.0.210:2999/redmine/issues/2318)
---
## VM HSM模擬器
to run the HSM simulator
$ cd /opt/utimaco/se_sim/bin
$ ./cs_sim.sh
after successfully run simulator, run the service
$ cd /root/EXE
$ ./srv_mng
choose start HSM service (s)
$ ./promcmd
start using by sending command (e.g. NC or AS)