Compare commits

...

11 Commits

Author SHA1 Message Date
Asif Bacchus a4ba5ec8ba add TOC to readme 2020-06-20 09:08:05 -06:00
Asif Bacchus 2b5f2f04f0 update readme with POSH info 2020-06-20 09:07:13 -06:00
Asif Bacchus 6b9ca6a38c delete original reference script 2020-06-20 09:07:01 -06:00
Asif Bacchus bb6bcc5f78 minor changes to in-script help 2020-06-20 08:27:12 -06:00
Asif Bacchus 57e6c0e302 add in-script help 2020-06-20 08:19:53 -06:00
Asif Bacchus f22fedf88c process file-list 2020-06-20 07:43:27 -06:00
Asif Bacchus ac41f6fe48 move get-content into try, silence errors 2020-06-20 07:33:48 -06:00
Asif Bacchus 8a04d654ef move get-content into try, silence errors 2020-06-20 07:31:59 -06:00
Asif Bacchus 5c6c09b24f new ps script, process directory with filter 2020-06-20 07:26:21 -06:00
Asif Bacchus 6a15d54f08 rename original base ps script as reference 2020-06-20 07:25:45 -06:00
Asif Bacchus bf7fd94ec5 add basic single-file PS base script 2020-06-20 06:00:34 -06:00
2 changed files with 205 additions and 4 deletions

View File

@ -1,20 +1,28 @@
# Sub-Resource Integrity Hash Generator Scripts
# Sub-Resource Integrity Hash Generator Scripts <!-- omit in TOC -->
Basic scripts to generate SRI hashes. POSIX-compliant shell script for use on *nix and PowerShell for use on Windows.
- [common features](#common-features)
- [Linux script](#linux-script)
- [copy to path location](#copy-to-path-location)
- [troubleshooting](#troubleshooting)
- [PowerShell (POSH) script](#powershell-posh-script)
- [execution policy](#execution-policy)
- [final thoughts](#final-thoughts)
## common features
- Hash individual files or a quoted space-delimited list of files.
- Hash individual files or a list of files.
- Hash all files within a specified directory with one command.
- Hash a filtered-list of files within a directory with one command.
- Process a list of files and a directory (filtered or not) at the same time, saving you typing!
## linux script
## Linux script
- This script *requires* openssl be installed and will exit if it cannot find openssl.
- You can rename *sri* to anything you like.
- I suggest copying *sri* somewhere like */usr/local/bin* or */usr/bin* so it can be run easier and from anywhere (see note below).
- Complete help is included in the script. Simply run without any parameters or run with '*--help*'.
- Complete instructions are included in the script. Simply run without any parameters or run with '*--help*'.
```bash
./sri --help
@ -60,3 +68,31 @@ ls -lA /path/to/sri
# -rwxr-xr-x 1 user user 3622 Jun 20 01:18 sri
# note the x's --> -rwXr-Xr-X (capitals for emphasis)
```
## PowerShell (POSH) script
- You can rename this script to anything you want.
- I suggest copying this script to a simple path since you must execute POSH scripts using their full path.
- Complete instructions are included in the script. Run `Get-Help` as you would with any other POSH script.
```powershell
Get-Help .\sri.ps1 # basic help including syntax
Get-Help .\sri.ps1 -examples # detailed examples of script usage
Get-Help .\sri.ps1 -detailed # full help document
```
### execution policy
By default, Windows does not permit running any POSH scripts. You can change this behaviour by opening PowerShell as an administrator and entering the following command:
```powershell
Set-ExecutionPolicy RemoteSigned
```
This will allow scripts created on your machine to run as well an as *signed* scripts created on other machines. My script is signed, so it should run without any problems. This setting is far safer than bypassing the execution policy.
You can search for alternate bypass methods, but I have not included them here since switching to *RemoteSigned* is the technically correct approach.
## final thoughts
I hope these scripts help you out! If you have any comments, suggestions or improvements, please file an issue. I love getting feedback and learning new ways of doing things. For more scripts like this or solutions to common computing annoyances, check out my blog at [MyTechieThoughts.com](https://mytechiethoughts.com).

165
sri.ps1 Normal file
View File

@ -0,0 +1,165 @@
<# Create SRI hashes for specified files or directory contents #>
<#
.SYNOPSIS
Create Sub-Resource Integrity (SRI) SHA hashes for specified files or directory contents.
.\sri.ps1 -files file1[, file2, ...] -directory /path/to/directory [-filter filter] [-hashAlgo sha256|sha384|sha512]
.DESCRIPTION
Create Sub-Resource Integrity (SRI) SHA-256, SHA-384 or SHA-512 hashes for a specified list of files, a subset of files within a directory, or all files within a directory.
.PARAMETER files
A comma-separated list of files (full path suggested) for which to generate SRI hashes.
EXAMPLE: style.css
EXAMPLE: /some/path/style.css
EXAMPLE: style.css, /some/other/path/menu.css
ALIAS: file, list
.PARAMETER directory
Directory containing files for which to generate SRI hashes. Can be filtered using the 'filter' parameter.
EXAMPLE: $env:userprofile\myWebSite\css
EXAMPLE: C:\Websites\Website1\js
.PARAMETER filter
Process only files matching this criteria. Only relevant for directory operations.
DEFAULT: * (all files)
EXAMPLE: *.css
EXAMPLE: script-site1*.js
ALIAS: only, include
.PARAMETER hashAlgo
Use the specified algorithm to generate SRI hashes. Accepts sha256, sha384 (default), sha512.
DEFAULT: sha384
ALIAS: algorithm
.EXAMPLE
.\sri.ps1 style.css
Generate default SHA384 hash for 'style.css' located in the current directory.
.EXAMPLE
.\sri.ps1 style.css, c:\websites\css\menu.css, $env:userprofile\Documents\website\script.js
Generate default SHA384 hashes for 'style.css' in the current directory along with the other two files as specified by their full paths.
.EXAMPLE
.\sri.ps1 -directory c:\website\css -hashAlgo sha256
Generate SHA256 hashes for all files in the 'C:\Website\css' directory
.EXAMPLE
.\sri.ps1 -dir c:\website\includes -filter *.js -algo sha512
Generate SHA512 hashes (partial alias used for '-hashAlgo') for all files matching '*.js' in directory 'C:\website\includes'
.EXAMPLE
.\sri.ps1 -files img\logo.svg, media\video.mp4 -directory css
Generate default SHA384 hashes for 'logo.svg' and 'video.mp4' in sub-folders 'img' and 'media', respectively, of the current folder. Then also generate hashes for all files in folder 'css', also a sub-folder of the current folder.
#>
param (
# List of files to hash
[Parameter(HelpMessage="Comma-separated list of files to hash.")]
[Alias("file", "list")]
[ValidateNotNullOrEmpty()]
[string[]]
$files,
# Directory of files to hash
[Parameter(HelpMessage="Hash all files within this directory.")]
[ValidateNotNullOrEmpty()]
[string]
$directory,
# File filter to apply to directory operations
[Parameter(HelpMessage="Only hash files of this type, relevant only when processing a directory.")]
[Alias("only", "include")]
[ValidateNotNullOrEmpty()]
[string]
$filter = '*',
# Hash algorithm to use
[Parameter(HelpMessage="Hash algorithm to use (SHA256, SHA384, SHA512).")]
[Alias("algorithm")]
[ValidateSet('sha256', 'sha384', 'sha512')]
[string]
$hashAlgo = 'sha384'
)
function displayError($returnCode, $eMsg){
Write-Host "`nERROR: $eMsg" -ForegroundColor Red
Write-Host "Exiting.`n" -ForegroundColor Red
exit $returnCode
}
function hashSHA($type){
switch($type){
'sha256' { return [System.Security.Cryptography.SHA256]::Create() }
'sha384' { return [System.Security.Cryptography.SHA384]::Create() }
'sha512' { return [System.Security.Cryptography.SHA512]::Create() }
default{
displayError 2 'Unknown hash algorithm.'
}
}
}
function doHash($file, $hash){
try{
$fileContents = Get-Content $file -Raw -ErrorAction SilentlyContinue
$hashBytes = $hash.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($fileContents))
return [System.Convert]::ToBase64String($hashBytes)
}
catch{
return 1
}
}
# instantiate hash provider
$hashAlgo = $hashAlgo.ToLower()
$hash = hashSHA $hashAlgo
# process directory, if specified
if ($directory){
# continue only if directory exists, otherwise exit with error
if (Test-Path -Path $directory){
Write-Host "Processing directory: $directory" -ForegroundColor Cyan
Get-ChildItem -Path $directory -Filter $filter | ForEach-Object({
$hashValue = doHash $directory\$_ $hash
if ($hashValue -ne 1){
Write-Host "$_ --> $hashAlgo-$hashValue" -ForegroundColor Green
}
else{
Write-Host "$_ --> unable to hash file" -ForegroundColor Red
}
})
}
else{
displayError 1 "Directory '$directory' does not exist."
}
}
# process file list, if specified
if ($files) {
Write-Host "Processing files:" -ForegroundColor Cyan
foreach ($file in $files) {
if (Test-Path -Path $file){
$hashValue = doHash $file $hash
if ($hashValue -ne 1){
Write-Host "$file --> $hashAlgo-$hashValue" -ForegroundColor Green
}
else {
Write-Host "$file --> unable to hash file" -ForegroundColor Red
}
}
else{
Write-Host "$file --> cannot find file" -ForegroundColor Red
}
}
}
# clean up and exit
Write-Host
$hash.Dispose()
exit 0
#EOF