Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define MPRIME_LEN (8 + RSA_SALT_SIZE + RSA_SALT_SIZE)
- #define MPRIME_OCTETS 0
- #define MPRIME_MHASH (MPRIME_OCTETS + 8)
- #define MPRIME_SALT (MPRIME_MHASH + RSA_SALT_SIZE)
- #define DB_END (-1)
- #define DB_MPRIME_HASH ((DB_END) + (-RSA_SALT_SIZE))
- #define DB_SALT ((DB_MPRIME_HASH) + (-RSA_SALT_SIZE))
- #define DB_MASK_BYTE ((DB_SALT) + (-1))
- #define DB_PADDING_END ((DB_MASK_BYTE) + (-1))
- size_t hashlib_RSAEncodePSS(
- const uint8_t* in,
- size_t len,
- uint8_t *out,
- size_t modulus_len,
- uint8_t *salt){
- uint8_t mprime_buf[MPRIME_LEN];
- SHA256_CTX ctx;
- uint32_t mbuffer[64];
- uint8_t hMprime[RSA_SALT_SIZE];
- uint8_t mgf1_digest[RSA_MODULUS_MAX - RSA_SALT_SIZE - 1];
- size_t db_len = modulus_len - RSA_SALT_SIZE - 1;
- size_t ps_len = db_len - RSA_SALT_SIZE - 1;
- // errors
- if((in == NULL) || (out == NULL)) return 0;
- if((modulus_len > 256) || (modulus_len < 128)) return 0;
- if(len==0) return 0;
- // init buffers to 0
- memset(out, 0, modulus_len);
- memset(mprime_buf, 0, MPRIME_LEN);
- // hash message, write to MHASH block
- hashlib_Sha256Init(&ctx, mbuffer);
- hashlib_Sha256Update(&ctx, in, len);
- hashlib_Sha256Final(&ctx, &mprime_buf[MPRIME_MHASH]);
- // write in random oracle passed, or generate one
- if(salt != NULL)
- memcpy(&mprime_buf[MPRIME_SALT], salt, RSA_SALT_SIZE);
- else
- hashlib_RandomBytes(&mprime_buf[MPRIME_SALT], RSA_SALT_SIZE);
- // copy salt to DB as well
- memcpy(&out[modulus_len + DB_SALT], &mprime_buf[MPRIME_SALT], RSA_SALT_SIZE);
- // write masking and ending bytes
- out[modulus_len + DB_MASK_BYTE] = 0x01;
- out[modulus_len + DB_END] = 0xbc;
- // hash M' buffer
- hashlib_Sha256Init(&ctx, mbuffer);
- hashlib_Sha256Update(&ctx, mprime_buf, MPRIME_LEN);
- hashlib_Sha256Final(&ctx, hMprime);
- // write hash to output hash block
- memcpy(&out[modulus_len + DB_MPRIME_HASH], hMprime, RSA_SALT_SIZE);
- // MGF1 the hash
- hashlib_MGF1Hash(hMprime, RSA_SALT_SIZE, mgf1_digest, db_len);
- // xor the hash with the output db block
- for(size_t i = 0; i < db_len; i++)
- out[i] ^= mgf1_digest[i];
- return modulus_len;
- }
- bool hashlib_RSAVerifyPSS(const uint8_t *in, size_t len, const uint8_t *expected, size_t modulus_len){
- uint8_t mgf1_digest[RSA_MODULUS_MAX - RSA_SALT_SIZE - 1];
- uint8_t self_sig_buf[RSA_MODULUS_MAX];
- uint8_t salt[32];
- size_t db_len = modulus_len - RSA_SALT_SIZE - 1;
- memcpy(self_sig_buf, expected, modulus_len);
- hashlib_MGF1Hash(&self_sig_buf[modulus_len + DB_MPRIME_HASH], RSA_SALT_SIZE, mgf1_digest, db_len);
- for(size_t i = 0; i < db_len; i++)
- self_sig_buf[i] ^= mgf1_digest[i];
- memcpy(salt, &self_sig_buf[modulus_len + DB_SALT], 32);
- hashlib_RSAEncodePSS(in, len, self_sig_buf, modulus_len, salt);
- return hashlib_CompareDigest(self_sig_buf, expected, modulus_len);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement