Implement unpad for ISO 7816 padding.
Chaos Ci / test (push) Successful in 3m11s
Chaos Ci / benchmark (push) Successful in 1m52s

This commit is contained in:
hashlag
2026-08-13 00:31:40 +03:00
parent 4e5627b503
commit ac122f0f9f
2 changed files with 261 additions and 0 deletions
+49
View File
@@ -1,9 +1,12 @@
#ifndef CHAOS_PADDING_PADDERISO7816_HPP
#define CHAOS_PADDING_PADDERISO7816_HPP
#include <cstddef>
#include <cstdint>
#include <limits>
#include "Padding/Padder.hpp"
#include "Service/Branchless.hpp"
namespace Chaos::Padding
{
@@ -26,6 +29,52 @@ public:
}
}
}
struct ComputeUnpadResult
{
bool IsOkay_;
uint8_t PadSize_;
};
template<typename InputIt>
static ComputeUnpadResult ComputeUnpad(InputIt begin, InputIt end) noexcept
{
if (begin == end)
{
return { .IsOkay_ = false, .PadSize_ = 0 };
}
uint8_t padSizeIncrement = 1;
uint8_t padSize = 0;
uint8_t encountered0x80 = 0x00;
uint8_t onlyZerosPast0x80 = 0xFF;
InputIt it = end;
while (it != begin && padSize < std::numeric_limits<uint8_t>::max())
{
--it;
const uint8_t byte = *it;
padSizeIncrement = Branchless::Sel<uint8_t>(encountered0x80, 0, 1);
encountered0x80 |= Branchless::Eq<uint8_t, uint8_t>(byte, 0x80);
onlyZerosPast0x80 &= Branchless::IsZero<uint8_t, uint8_t>(byte) | encountered0x80;
padSize += padSizeIncrement;
}
uint8_t isOkay = encountered0x80 & onlyZerosPast0x80;
return
{
.IsOkay_ = static_cast<bool>(isOkay),
.PadSize_ = Branchless::Sel<uint8_t>(isOkay, padSize, 0)
};
}
private:
using Branchless = Service::Branchless;
};
} // namespace Chaos::Padding