Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @param pbRecvBuffer response from PICC after 0xAA00, including 0xAF
- */
- private bool check_authentication_aes(byte[] pbRecvBuffer)
- {
- // From: http://stackoverflow.com/questions/21257442/mifare-desfire-ev1-authentication-using-aes
- int keylength = pbRecvBuffer.Length - 1;
- byte[] rndb_enc = new byte[keylength];
- // 3 Receive Encrypted(RndB) from PICC
- System.Buffer.BlockCopy(pbRecvBuffer, 1, rndb_enc, 0, keylength);
- logger.Debug("rndb_enc: " + HexFormatting.DumpHex(rndb_enc));
- // 5 Decrypt Using AES with IV = 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 (16byte all 0s)
- byte[] rndb_dec = this.decipherAES(rndb_enc, new byte[16]);
- logger.Debug("rndb_dec: " + HexFormatting.DumpHex(rndb_dec));
- // 6 Rotate Left (Left Shift) RndB producing RndB’
- byte[] rndb_dec_rot = new byte[keylength];
- System.Buffer.BlockCopy(rndb_dec, 0, rndb_dec_rot, 0, keylength);
- Rotate<byte>(rndb_dec_rot);
- logger.Debug("rndb_dec_rot: " + HexFormatting.DumpHex(rndb_dec_rot));
- // 7 Generate RndA
- byte[] rnda = new byte[keylength];
- new Random().NextBytes(rnda);
- logger.Debug("rnda: " + HexFormatting.DumpHex(rnda));
- // 8 Encrypted RndA using IV = #step3 (Encrypted RndB received from PICC)
- byte[] rnda_enc = this.decipherAES(rnda, rndb_enc);
- logger.Debug("rnda_enc: " + HexFormatting.DumpHex(rnda_enc));
- // 9 Encrypt RndB’ using IV = #step8 (Encrypted RndA)
- byte[] rndb_dec_rot_enc = this.decipherAES(rndb_dec_rot, rnda_enc);
- logger.Debug("rndb_rot_enc: " + HexFormatting.DumpHex(rndb_dec_rot_enc));
- // 10 Send APDU (Data = RndA+RndB’)
- String to_send_str = "AF " + HexFormatting.DumpHex(rnda_enc) + " " + HexFormatting.DumpHex(rndb_dec_rot_enc);
- logger.Debug("to_send_str: " + to_send_str);
- return reader.Transmit(HexEncoding.GetBytes(to_send_str), 0x9000);
- }
- static void Rotate<T>(T[] source)
- {
- T temp = source[0];
- Array.Copy(source, 1, source, 0, source.Length - 1);
- source[source.Length - 1] = temp;
- }
- private byte[] decipherAES(byte[] bytes, byte[] iv)
- {
- byte[] key = new byte[16];
- KeyParameter aesKeyParam = ParameterUtilities.CreateKeyParameter("AES", key);
- IBufferedCipher c = CipherUtilities.GetCipher("AES/CBC/NoPadding");
- c.Init(false, new ParametersWithIV(aesKeyParam, iv));
- return c.DoFinal(bytes);
- }
Advertisement
Add Comment
Please, Sign In to add comment