using System;
using System.Security.Cryptography;
using System.Text;
namespace CarpaNet.OAuth.Crypto;
///
/// PKCE (Proof Key for Code Exchange) implementation (RFC 7636).
///
public static class Pkce
{
///
/// The default verifier length in bytes (produces 43 character base64url string).
///
public const int DefaultVerifierByteLength = 32;
///
/// Generates a cryptographically random code verifier.
///
/// The number of random bytes to generate (default: 32, produces 43 chars).
/// A base64url-encoded code verifier.
public static string GenerateVerifier(int byteLength = DefaultVerifierByteLength)
{
var bytes = new byte[byteLength];
using var rng = RandomNumberGenerator.Create();
rng.GetBytes(bytes);
return Base64UrlEncode(bytes);
}
///
/// Computes the S256 code challenge from a code verifier.
///
/// The code verifier.
/// The base64url-encoded SHA-256 hash of the verifier.
public static string ComputeChallenge(string verifier)
{
using var sha256 = SHA256.Create();
var hash = sha256.ComputeHash(Encoding.ASCII.GetBytes(verifier));
return Base64UrlEncode(hash);
}
///
/// Generates a PKCE code verifier and challenge pair.
///
/// A tuple containing the verifier and its S256 challenge.
public static (string Verifier, string Challenge) Generate()
{
var verifier = GenerateVerifier();
var challenge = ComputeChallenge(verifier);
return (verifier, challenge);
}
///
/// Generates a cryptographically random state parameter.
///
/// The number of random bytes to generate.
/// A base64url-encoded state value.
public static string GenerateState(int byteLength = 16)
{
var bytes = new byte[byteLength];
using var rng = RandomNumberGenerator.Create();
rng.GetBytes(bytes);
return Base64UrlEncode(bytes);
}
///
/// Generates a cryptographically random nonce.
///
/// The number of random bytes to generate.
/// A base64url-encoded nonce value.
public static string GenerateNonce(int byteLength = 16)
{
return GenerateState(byteLength);
}
///
/// Encodes bytes as base64url (RFC 4648).
///
public static string Base64UrlEncode(byte[] bytes)
{
return Convert.ToBase64String(bytes)
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
}
///
/// Decodes a base64url string to bytes (RFC 4648).
///
public static byte[] Base64UrlDecode(string input)
{
var base64 = input.Replace('-', '+').Replace('_', '/');
// Add padding if needed
var remainder = base64.Length % 4;
if (remainder == 2)
{
base64 += "==";
}
else if (remainder == 3)
{
base64 += "=";
}
return Convert.FromBase64String(base64);
}
}