CipherShift365.Core.Analysis
Package: CipherShift365.Core.Analysis
Target: .NET 9 / .NET 10
Role: Cryptographic discovery engine — Roslyn source analysis, dependency assembly scanning, X.509 certificate parsing, confidence strategy, and end-to-end analysis pipeline orchestration.
Table of Contents
- What It Does
- Why It's Needed (Value Proposition)
- Installation
- How to Run / Use
- User Manual
- Developer Manual
- Code Examples
- API Reference
- Configuration Options
What It Does
CipherShift365.Core.Analysis discovers every cryptographic usage across a .NET project — source code, compiled assemblies, and X.509 certificates — classifies each finding by quantum risk, and generates a prioritized migration plan. It is the "where is the crypto?" engine.
The analysis pipeline has seven stages:
Source Discovery (
RoslynSourceDetector) — Parses C# source files using Roslyn semantic analysis. Resolves actual types at call sites (invocations ofRSA.Create(),new AesGcm(...), etc.) and maps them to algorithm names, roles, and parameters.Dependency Discovery (
DependencyDetector) — Scans DLLs in the project tree viaSystem.Reflection.PortableExecutable. Inspects IL metadata to find type references and member references that match known crypto APIs.Certificate Discovery (
CertConfigDetector) — Parses X.509 certificate files (.cer,.crt,.pfx,.p12,.pem,.der). Extracts signature algorithms, public key algorithms, and key sizes. Flags expired certificates.Identity & Classification — Every detected usage is assigned a
LogicalIdandLocationalIdviaIIdentityService, then classified byIRiskModelinto a quantum risk tier.Recommendation — The knowledge base recommends a PQC replacement for each non-safe finding. Fallback: ML-DSA-65 for signatures, ML-KEM-768 for KEM/KEX, AES-256-GCM for symmetric, SHA-512 for hashing.
Effort Estimation (
EffortEstimator) — Estimates person-days required to migrate each finding based on algorithm complexity, location type, and risk level.Prioritization & Plan (
PlanPrioritizer) — Orders migration items by urgency (Critical→High→Medium→Low) considering data sensitivity, risk level, and regulatory deadlines.
Key Components
| Component | File | Purpose |
|---|---|---|
AnalysisEngine |
AnalysisEngine.cs |
Orchestrates detector execution, file discovery, CBOM generation |
DiscoveryPipeline |
Pipeline/DiscoveryPipeline.cs |
Full pipeline: scan → classify → recommend → score → CBOM → sign → plan → estimate |
RoslynSourceDetector |
Detectors/RoslynSourceDetector.cs |
Semantic source code analysis |
DependencyDetector |
Detectors/DependencyDetector.cs |
IL metadata inspection of assemblies |
CertConfigDetector |
Detectors/CertConfigDetector.cs |
X.509 certificate parsing |
CryptoApiRegistry |
CryptoApiRegistry.cs |
Registry of known .NET crypto APIs with mappings |
CryptoPatternDetector |
CryptoPatternDetector.cs |
Standalone detector for syntax trees and assemblies |
AssessmentService |
AssessmentService.cs |
Organizational readiness assessment with scoring |
ConfidenceStrategy |
ConfidenceStrategy.cs |
Defines confidence tiers per detection method |
PlanPrioritizer |
Pipeline/PlanPrioritizer.cs |
Sorts migration items by urgency |
EffortEstimator |
Pipeline/EffortEstimator.cs |
Computes migration effort estimates |
Why It's Needed
Manual cryptographic inventory is error-prone, slow, and incomplete. A typical enterprise .NET application uses cryptography in dozens of places: authentication, token validation, data encryption, hashing, TLS, certificate management, and dependency assemblies. Without automated discovery, teams cannot answer basic questions:
- "Where does our code use RSA?"
- "Which assemblies reference
ECDiffieHellman?" - "Do we have certificates signed with SHA-1 or MD5?"
- "How many person-days would it take to migrate to ML-DSA?"
Value Showcase
| Capability | Value |
|---|---|
| Semantic source detection | Finds crypto at the type level, not regex — Confidence.High |
| IL scanning | Discovers crypto in third-party NuGet packages without source access |
| Certificate scanning | Maps every certificate in the project tree to its crypto algorithms |
| Automatic CBOM generation | Every scan produces a CycloneDX 1.6 CBOM |
| Migration plan | Prioritized, effort-estimated replacement plan for every finding |
| CI/CD ready | Pipeline can be embedded in build scripts and GitHub Actions |
| Readiness assessment | Structured questionnaire with quantitative scoring (0–100%) |
| CNSA 2.0 validation | Validates findings against CNSA 2.0 approved algorithms |
Installation
<PackageReference Include="CipherShift365.Core.Analysis" Version="1.0.0" />
Transitive dependencies include:
CipherShift365.Core.RuntimeMicrosoft.CodeAnalysis.CSharp(Roslyn)System.Reflection.Metadata(assembly inspection)
dotnet add package CipherShift365.Core.Analysis
How to Run / Use
Basic Analysis
using CipherShift365.Core.Runtime;
using CipherShift365.Core.Analysis;
var kb = new InMemoryKnowledgeBase(
new KbVersion(1, 0, 0),
new[] { new KbEntry("RSA", CryptoRole.Signature, RiskLevel.QuantumBroken) });
var identity = new IdentityService();
var riskModel = new RiskModel(kb);
var engine = new AnalysisEngine(riskModel);
var context = new AnalysisContext(
"./MyProject",
kb,
identity);
var result = await engine.AnalyzeAsync(context);
Console.WriteLine($"Findings: {result.Findings.Count}");
Console.WriteLine($"Duration: {result.Duration.TotalMilliseconds}ms");
Console.WriteLine($"Success: {result.Success}");
Full Pipeline
var kb = CreateKnowledgeBase();
var identity = new IdentityService();
var riskModel = new RiskModel(kb);
var policyEngine = new PolicyEngine(riskModel);
var engine = new AnalysisEngine(riskModel);
var signer = new HmacSigner(Encoding.UTF8.GetBytes("32-byte-secret-key--mandatory!"));
var pipeline = new DiscoveryPipeline(engine, kb, identity, riskModel, policyEngine, signer);
var report = await pipeline.RunAsync("./MyProject");
Console.WriteLine($"Score: {report.TotalSystemScore:F2}");
Console.WriteLine($"Plan items: {report.Plan.Items.Count}");
Console.WriteLine($"Effort: {report.Plan.TotalEffortPersonDays} person-days");
User Manual
Detection Methods
The analysis engine runs three detectors in sequence:
1. Roslyn Source Analyzer (Confidence: High)
Scans all *.cs files in the project, excluding \obj\ and \bin\ directories. Uses Roslyn to create a compilation and get semantic models for each syntax tree.
Detection targets:
InvocationExpressionSyntax— e.g.,RSA.Create(),SHA256.HashData(...),AesGcm.Encrypt(...)ObjectCreationExpressionSyntax— e.g.,new HMACSHA256(key),new Rfc2898DeriveBytes(...)
When Roslyn semantic model resolution fails, falls back to syntax-only detection. Extracts numeric literal parameter values when available (e.g., key sizes from constructor arguments).
2. Dependency Analyzer (Confidence: Medium)
Enumerates all *.dll files in the project tree (excluding \obj\, \ref\, \TestResults\). Opens each assembly using System.Reflection.PortableExecutable.PEReader and inspects:
TypeReferenceentries — matches againstCryptoApiRegistryMemberReferenceentries — resolves parent type and matches type+method against the registry
Since parameters cannot be fully resolved from IL metadata, these findings carry Confidence.Medium.
3. Certificate/Config Parser (Confidence: High)
Discovers certificate files by extension: .cer, .crt, .pfx, .p12, .pem, .der. For each certificate:
- Extracts signature algorithm OID and maps to algorithm names (RSA, ECDSA, DSA, SHA-256, etc.)
- Extracts public key algorithm and key size
- Flags expired certificates as
Mitigablerisk
Algorithm mapping supports common OID friendly names: sha256RSA, sha384ECDSA, ecdsa-with-SHA256, RSA, DSA, etc.
Crypto API Registry
The CryptoApiRegistry contains a hardcoded list of 21 known .NET crypto APIs. Each CryptoApiMapping records:
| Field | Example |
|---|---|
FullyQualifiedName |
System.Security.Cryptography.RSA |
TypeShortName |
RSA |
MethodName |
Create |
Algorithm |
RSA |
Role |
Signature |
DefaultParameters |
Optional key sizes, modes, padding |
Lookup methods:
ResolveByTypeAndMethod(typeName, methodName)— exact matchResolveByTypeName(typeName)— match on type name onlyResolve(fullyQualifiedName)— substring match on full name
CNSA 2.0 Validation
The CnsaValidator validates findings against CNSA 2.0 approved algorithms. It produces a CnsaValidationResult with:
- Per-finding verdicts (
CnsaAssetVerdict) - Gap items for non-compliant findings (
CnsaGapItem) - Evidence tracking (
CnsaEvidence)
Organizational Readiness Assessment
The AssessmentService provides a structured assessment with sections covering:
- Organizational & Regulatory Context
- Estate & .NET/Azure Profile
- Cryptographic Inventory Maturity
- Data Sensitivity & Longevity (HNDL)
- Migration Readiness
- Governance & Timeline
Each section has scored questions. Responses generate a ReadinessPercent (0–100) and category-specific recommendations.
Developer Manual
Architecture
CipherShift365.Core.Analysis
├── IAnalysisEngine.cs # Public interface
├── AnalysisEngine.cs # Main engine: orchestrates detectors
├── AnalysisContext.cs / AnalysisResult.cs # Request/response models
├── ConfidenceStrategy.cs # Confidence tier constants
├── CryptoApiMapping.cs # API→algorithm mapping record
├── CryptoApiRegistry.cs # Static registry of known APIs
├── CryptoPatternDetector.cs # Standalone detector
├── AssessmentService.cs # Readiness assessment engine
├── DefaultAssessmentTemplate.cs # Pre-built questionnaire
├── CNSA/ # CNSA 2.0 validation
│ ├── CnsaValidator.cs
│ ├── CnsaProfileFactory.cs
│ ├── CnsaValidationResult.cs
│ └── ...
├── Detectors/
│ ├── IDetector.cs # Detector contract + DetectorContext
│ ├── RoslynSourceDetector.cs # Semantic C# analysis
│ ├── DependencyDetector.cs # IL metadata scanning
│ └── CertConfigDetector.cs # X.509 parsing
└── Pipeline/
├── DiscoveryPipeline.cs # Full end-to-end pipeline
├── DiscoveryReport.cs # Pipeline output
├── PlanPrioritizer.cs # Urgency sorting
├── EffortEstimator.cs # Person-day estimation
├── MigrationItem.cs # Single migration step
└── MigrationPlan.cs # Ordered plan with total effort
Detector Interface
All detectors implement:
public interface IDetector
{
string Name { get; }
Confidence Confidence { get; }
IReadOnlyList<Finding> Detect(DetectorContext context, CancellationToken ct = default);
}
The DetectorContext carries file path, project path, identity service, risk model, and KB version — everything a detector needs to produce fully-classified findings.
Adding a New Crypto API
To add a new crypto API to the registry, edit CryptoApiRegistry.cs:
// Add to KnownApis array:
new CryptoApiMapping(
"System.Security.Cryptography.X509Certificates.X509Certificate2",
"X509Certificate2",
".ctor",
"X.509",
CryptoRole.Other,
Description: "X.509 certificate handling"),
The new mapping is immediately available to all detectors via ResolveByTypeName and ResolveByTypeAndMethod.
Creating a Custom Detector
public sealed class MyCustomDetector : IDetector
{
public string Name => "Custom Detector";
public Confidence Confidence => ConfidenceStrategy.SemanticResolved;
public IReadOnlyList<Finding> Detect(DetectorContext context, CancellationToken ct = default)
{
// 1. Discover assets
// 2. Map to algorithm/role
// 3. Classify via context.RiskModel
// 4. Compute IDs via context.IdentityService
// 5. Return findings
}
}
Register it by adding to the detector list in AnalysisEngine.AnalyzeAsync or by composing the pipeline externally.
Pipeline Flow
RunAsync(projectPath)
└─► AnalysisContext creation
└─► AnalysisEngine.AnalyzeAsync
├─► File discovery (*.cs files)
├─► RoslynSourceDetector.Detect (per file)
├─► DependencyDetector.Detect (all assemblies)
└─► CertConfigDetector.Detect (all certs)
└─► Enrich findings (re-classify)
└─► Build recommendations (per finding)
└─► Build effort estimates (per finding)
└─► PolicyEngine.Evaluate (produces verdict)
└─► Score system
└─► Generate CBOM
└─► Sign CBOM (if signer configured)
└─► Build migration plan (prioritize + estimate total)
└─► Return DiscoveryReport
File Discovery
The analysis engine auto-discovers source files:
- Pattern:
*.cs - Recursive, all directories
- Excludes
\obj\and\bin\ - Capped at 10,000 files
Users can pass explicit file lists via AnalysisContext.SourceFiles to skip discovery.
Assembly Scanning Details
DependencyDetector uses System.Reflection.PortableExecutable for assembly scanning:
- Opens assembly as a
PEReaderstream - Checks
peReader.HasMetadatabefore proceeding - Enumerates
TypeReferenceHandleandMemberReferenceHandle - Resolves type names and namespaces from metadata strings
- Matches against
CryptoApiRegistryusing type name, then by full name if need be
Code Examples
Running a Targeted Analysis
var context = new AnalysisContext(
ProjectPath: "./MyAspireApp",
KnowledgeBase: kb,
IdentityService: new IdentityService(),
SourceFiles: new[] { "Auth/JwtService.cs", "Crypto/AesEncryption.cs" },
Options: new AnalysisOptions(
ScanSource: true,
ScanAssemblies: false,
GenerateCbom: true));
var result = await engine.AnalyzeAsync(context);
Readiness Assessment
var assessment = new AssessmentService();
var template = assessment.GetTemplate("pqc-readiness-v1");
var answers = new[]
{
new QuestionAnswer("q1.1", "Yes, fully applicable", 15),
new QuestionAnswer("q3.1", "In progress", 8),
// ... all 18 questions
};
var response = assessment.Submit("pqc-readiness-v1", "security-team@company.com", answers);
var score = assessment.Score(response);
Console.WriteLine($"Readiness: {score.ReadinessPercent}%");
Console.WriteLine(score.Summary);
// "Advanced readiness — organization is well-prepared for PQC migration."
CNSA 2.0 Validation
var validator = new CnsaValidator();
var result = validator.Validate(findings);
Console.WriteLine($"CNSA Compliant: {result.Verdict.IsCompliant}");
foreach (var gap in result.GapItems)
{
Console.WriteLine($"Gap: {gap.Description} → {gap.Recommendation}");
}
Full Pipeline with Baseline Policy
var pipeline = new DiscoveryPipeline(engine, kb, identity, riskModel, policyEngine, signer);
var baseline = new Baseline(
kb.Version,
DateTimeOffset.UtcNow,
previousScanFindings,
"Accepted risks as of 2026-06-01");
var report = await pipeline.RunAsync(
"./MyProject",
policyMode: PolicyMode.BaselineAware,
baseline: baseline);
if (!report.PolicyVerdict.IsCompliant)
{
Console.WriteLine($"New violations: {report.PolicyVerdict.Violations.Count}");
}
Using CryptoPatternDetector Directly
var detector = new CryptoPatternDetector(identity, riskModel, kb.Version);
// Analyze a specific syntax tree
var code = File.ReadAllText("CryptoHelper.cs");
var tree = CSharpSyntaxTree.ParseText(code);
var findings = detector.DetectInSyntaxTree(tree, "MyProject");
// Analyze a specific assembly
var assemblyFindings = detector.DetectInAssembly("path/to/ThirdParty.dll");
API Reference
IAnalysisEngine
| Method | Description |
|---|---|
AnalyzeAsync(AnalysisContext, CancellationToken) → Task<AnalysisResult> |
Runs all detectors and returns findings with optional CBOM |
AnalysisContext
| Property | Type | Description |
|---|---|---|
ProjectPath |
string |
Root directory of the project to scan |
KnowledgeBase |
IKnowledgeBase |
KB for risk classification and recommendations |
IdentityService |
IIdentityService |
For computing logical/locational IDs |
SourceFiles |
IReadOnlyList<string>? |
Explicit source file list (auto-discovered if null) |
AssemblyPaths |
IReadOnlyList<string>? |
Explicit assembly paths to scan |
Options |
AnalysisOptions? |
Scan configuration |
AnalysisOptions
| Property | Type | Default | Description |
|---|---|---|---|
ScanSource |
bool |
true |
Enable Roslyn source analysis |
ScanAssemblies |
bool |
true |
Enable dependency assembly scanning |
GenerateCbom |
bool |
true |
Generate a CycloneDX CBOM in the result |
DefaultConfidence |
Confidence |
High |
Default confidence for pattern detector |
AnalysisResult
| Property | Type | Description |
|---|---|---|
ProjectPath |
string |
Scanned project path |
KbVersion |
KbVersion |
KB version used for classification |
Findings |
IReadOnlyList<Finding> |
All detected crypto usages |
Cbom |
Cbom? |
Generated CBOM (if enabled) |
Duration |
TimeSpan |
Wall-clock scan time |
Success |
bool |
Whether the scan completed without errors |
ErrorMessage |
string? |
Error details if scan failed |
IDetector
| Property / Method | Description |
|---|---|
Name → string |
Human-readable detector name |
Confidence → Confidence |
Confidence level for all findings from this detector |
Detect(DetectorContext, CancellationToken) → IReadOnlyList<Finding> |
Run detection |
ConfidenceStrategy
| Static Property | Value | When Used |
|---|---|---|
SemanticResolved |
High |
Roslyn source detection, cert parsing |
DependencyInspected |
Medium |
IL assembly scanning |
CatalogAsserted |
Low |
Third-party catalog claims |
DiscoveryPipeline
| Constructor Parameter | Type | Description |
|---|---|---|
analysisEngine |
IAnalysisEngine |
Core analysis engine |
knowledgeBase |
IKnowledgeBase |
Knowledge base |
identityService |
IIdentityService |
Identity computation |
riskModel |
IRiskModel |
Risk classification |
policyEngine |
IPolicyEngine |
Policy evaluation |
signer |
ISigner? |
Optional CBOM signer |
factors |
PriorityFactors? |
Custom priority weights for plan |
DiscoveryReport
| Property | Type | Description |
|---|---|---|
Analysis |
AnalysisResult |
Raw analysis output |
SignedCbom |
Cbom |
Signed CBOM (or unsigned if no signer) |
Plan |
MigrationPlan |
Prioritized migration plan |
TotalSystemScore |
double |
0–1 system risk score |
IsComplete |
bool |
Whether pipeline completed successfully |
ErrorMessage |
string? |
Error details if incomplete |
HasCbom |
bool |
Computed: is CBOM non-null |
MigrationItem
| Property | Type | Description |
|---|---|---|
Finding |
Finding |
The crypto finding to migrate |
Recommendation |
Recommendation |
PQC replacement algorithm |
Urgency |
MigrationUrgency |
Critical, High, Medium, Low |
PriorityRationale |
string |
Human-readable reasoning |
Effort |
EffortEstimate |
Person-days estimate |
AssessmentService
| Method | Description |
|---|---|
GetTemplates() → IReadOnlyList<AssessmentTemplate> |
Available assessment templates |
GetTemplate(string) → AssessmentTemplate? |
Get specific template by ID |
Submit(templateId, actor, answers) → AssessmentResponse |
Submit assessment answers |
Score(AssessmentResponse) → AssessmentScore |
Compute readiness score |
GetResponses() → IReadOnlyList<AssessmentResponse> |
All submitted responses |
GetResponse(string) → AssessmentResponse? |
Specific response by ID |
Configuration Options
Analysis Options
Passed via AnalysisOptions in the AnalysisContext:
var options = new AnalysisOptions(
ScanSource: true, // Enable Roslyn detection
ScanAssemblies: true, // Enable IL scanning
GenerateCbom: true, // Generate CycloneDX output
DefaultConfidence: Confidence.High);
Priority Factors
Customize plan prioritization by passing PriorityFactors to DiscoveryPipeline:
var factors = new PriorityFactors(
DataSensitivityWeight: 1.5,
RiskLevelWeight: 1.0,
EffortWeight: 0.5);
var pipeline = new DiscoveryPipeline(engine, kb, identity, riskModel, policyEngine,
signer: null, factors: factors);
File Discovery Limits
- Maximum source files: 10,000 (per
AnalysisEngine.DiscoverSourceFiles) - Certificate files per extension: 100 (per
CertConfigDetector)
Detector Selection
Detectors are selected based on AnalysisOptions.ScanSource and AnalysisOptions.ScanAssemblies. The CertConfigDetector always runs (it's fast and critical for completeness).
Generated for CipherShift365 Core.Analysis. Part of the CipherShift365 PQC Readiness Platform.