Defang-String.psm1

function Defang-String {
    <#
    .SYNOPSIS
    Defangs or refangs URLs, email addresses, and IP addresses for safe handling.
 
    .DESCRIPTION
    This function modifies URLs, email addresses, and IPs to make them safe for sharing in security contexts:
    - http/https → hXXp/hXXps
    - ftp/sftp → fXp/sfXp
    - :// → [://]
    - :port → [:]port (only colon is defanged)
    - . → [.] except in email usernames
    If -Refang is specified, it reverses all defanging changes.
 
    .PARAMETER String
    One or more strings (URLs, emails, etc.) to process.
 
    .PARAMETER Refang
    If specified, undoes defanging and restores original formatting.
 
    .EXAMPLE
    Defang-String 'https://1.2.3.4:8080'
    hXXps[://]1[.]2[.]3[.]4[:]{8080}
 
    .EXAMPLE
    Defang-String 'bob@company.com'
    bob@company[.]com
 
    .EXAMPLE
    Defang-String 'hXXps[://]1[.]2[.]3[.]4[:]{8080}' -Refang
    https://1.2.3.4:8080
 
    .NOTES
    Ideal for use in cybersecurity contexts like malware analysis, email security, etc.
    #>


    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [string[]]$String,

        [switch]$Refang
    )

    process {
        foreach ($s in $String) {
            if ($Refang) {
                # Reverse defanging
                $s = $s -replace 'hXXps', 'https'
                $s = $s -replace 'hXXp', 'http'
                $s = $s -replace 'sfXp', 'sftp'
                $s = $s -replace 'fXp', 'ftp'
                $s = $s -replace '\[\://\]', '://'
                $s = $s -replace '\[\:\]', ':'
                $s = $s -replace '\[\.\]', '.'
            } 
            else {
                # Defang protocols
                $s = $s -replace '\bhttps\b', 'hXXps'
                $s = $s -replace '\bhttp\b', 'hXXp'
                $s = $s -replace '\bsftp\b', 'sfXp'
                $s = $s -replace '\bftp\b', 'fXp'

                # Defang :// separator
                $s = $s -replace '://', '[://]'

                # Defang only the colon in :PORT patterns (IPv4/IPv6 support)
                $s = $s -replace '(?<=\]|\w):(?=\d+)', '[:]'

                # Defang periods
                if ($s -like '*@*') {
                    # Defang only domain portion
                    $s = $s -replace '(@[^@\s]+?)\.', '$1[.]'
                } 
                else {
                    $s = $s -replace '\.', '[.]'
                }
            }

            $s
        }
    }
}