UnicodeDecodeError : 'utf-8'코덱이 위치 3에서 0xa1 바이트를 디코딩 할 수 없습니다. 잘못된 시작 바이트입니까?

DodgerMac

print (cipher.decrypt (pad (base64.b64decode (encrypted_string), 16)). decode ( 'utf-8')) UnicodeDecodeError : 'utf-8'코덱은 위치 3에서 0xa1 바이트를 디코딩 할 수 없습니다. 잘못된 시작 바이트

데이터 흐름 : 자바 스크립트 :

  1. 입력 = { "name": "abcd", "password": "abcd"}
  2. JSON.stringify (입력)
  3. CryptoJS는 CBC 모드로 AES를 암호화합니다.
  4. Base64 인코딩
  5. AJAX에서 Django로

Python3 / 장고 / PyCryptodome

  1. base64 디코딩
  2. Crypto.pad 16B
  3. Crypto.cipher.decrypt [성공]

수신 된 출력은 다음과 같습니다.

b'\xf5R\x0ck_\x90\xca\xcc\n\xe6S:\xed\xf1\x0f\x14\x1f\x8c_\x00\xd8m\x82\x96\xa3\x19K\xca\xc2\xfe\x14\x80\x8bD8\xcc\xdb\x91~\xa2~\xbf\xe5U\xe4\x12E`\xb5\r\xd8t\xbd=\xc0\x862\x837W6|\x07i\x8b\xb1"\xe9\xac}\xef\xf0\xf5\xa8\x0e\xf5z\xdc\xb0\xb5'

출력을 얻기 위해이 문자열을 디코딩하는 방법.


암호:


function toWordArray(str){
    return CryptoJS.enc.Utf8.parse(str);
}

function toString(words){
    return CryptoJS.enc.Utf8.stringify(words);
}

function toBase64String(words){
    return CryptoJS.enc.Base64.stringify(words);
}

function encrypt(input, key){
    console.log("Input: " + input);  
    var PROTOCOL_AES256 = 2;
    var secret_key = CryptoJS.SHA256(key);
    var header = toWordArray("AMAZON" + String.fromCharCode(PROTOCOL_AES256));
    var iv = CryptoJS.lib.WordArray.random(16);
    var body = CryptoJS.AES.encrypt(input, secret_key, {mode:CryptoJS.mode.CBC,iv: iv,padding:CryptoJS.pad.Pkcs7});

    // construct the packet
    // HEADER + IV + BODY
    header.concat(iv);
    header.concat(body.ciphertext);

    console.log("Bytes before Base64 encoding: " + header);
    // encode in base64
    return toBase64String(header);
}



$("#submitid").click(function(event) {
            event.preventDefault()
            // var encrypted = CryptoJS.AES(...);
            // var encrypted = CryptoJS.SHA256(...);
            var data = {};
            data["name"] = $("#nameid").val();
            data["password"] = $("#passwordid").val();
            var json_payload = JSON.stringify(data);

            var payload = encrypt(json_payload, key);
            console.log("Payload: " + payload);

            $.ajax({
                type: 'GET',
                url: "{% url 'Shenzen:actsignin' %}",
                data: {encrypted_string: payload},
                success: function(data,status,xhr){
                    console.log("AES sucessful withs status: "+status);
                },
                error: function(xhr,status,e) {
                    console.log("AES failed.");
                },
                async: true,
                datatype: 'json'
            })
        })

    },
    error: function(xhr,status,e) {
        console.log("error");
    },
    async: true,
    datatype: 'json'
});

Python3

def actsignin(request):
    global key
    global prime
    global base_num

    encrypted_string = request.GET['encrypted_string']

    print("Encrypted string decoded: ",base64.b64decode(encrypted_string).hex())
    print("----")
    protocol_aes = str(2)
    header_skip = 'AMAZON'+protocol_aes

    sha256_key = SHA256.new(data=bytes(key))
    cipher = AES.new(sha256_key.digest(),AES.MODE_CBC)
    print(cipher.decrypt(pad(base64.b64decode(encrypted_string),16)))
    print('in signin')
    # student = +Student.objects.get(name = name)
    # salt = student.salt
    # key = hashlib.pbkdf2_hmac('sha256',password.encode('utf-8'),salt,100000)
    # # Hash the password here to check
    # password_to_check_hashed = key
    # print(key)
    # print(student.password)
    # if student.password == key:
    return render(request,"Shenzen/display.html",{'student':'student'})
    # else:
    #     return render(request,"Shenzen/display.html",{'status':'failed'})

Maarten Bodewes
base64 decode
Crypto.pad 16B
Crypto.cipher.decrypt [successful]

에 의해 구현

cipher = AES.new(sha256_key.digest(),AES.MODE_CBC)
print(cipher.decrypt(pad(base64.b64decode(encrypted_string),16)))

이건 말이 안 돼. 순서는 패딩 한 다음 암호화하고 해독 한 다음 패딩 해제 합니다. 패딩 해제는 일반적으로 decrypt메서드 자체에서 수행됩니다 .

패딩을 해제 하는 동안 암호 해독 실패 할 수 있지만 패딩 해제 를 건너 뛰면 쓰레기를 받게됩니다. 암호문을 채우면 마지막 부분이 쓰레기라는 것은 확실합니다. 문자 디코딩은 결과 가비지 임을 알 수있는 첫 번째 장소 일뿐 입니다.

Python 코드의 기본값은 모두 0 IV이며 CryptoJS는 암호문 앞에 접두사가 붙은 모든 임의 IV를 명확하게 사용합니다.

인증 태그가 없으면 (MAC 또는 인증 된 암호에 의해 생성됨) 항상 암호 텍스트를 해독 할 수 있습니다. 일반적인 믿음에도 불구하고 블록 암호 해독은 실패하지 않습니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관