Skip to content

Instantly share code, notes, and snippets.

@DvdKhl
Last active August 1, 2023 13:32
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save DvdKhl/6139665 to your computer and use it in GitHub Desktop.
Save DvdKhl/6139665 to your computer and use it in GitHub Desktop.
Fast C# IBAN Checksum Verifier / Validation
//Copyright (C) 2013 DvdKhl
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
//to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
//and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//static bool IsIbanChecksumValid(ReadOnlySpan<char> iban) { //Use this line if you target a runtime which supports Spans
static bool IsIbanChecksumValid(string iban) {
if(iban.Length < 4 || iban[0] == ' ' || iban[1] == ' ' || iban[2] == ' ' || iban[3] == ' ') throw new InvalidOperationException();
var checksum = 0;
var ibanLength = iban.Length;
for(int charIndex = 0; charIndex < ibanLength; charIndex++) {
var c = iban[(charIndex + 4) % ibanLength];
if(c == ' ') continue;
int value;
if(c >= '0' && c <= '9') {
value = c - '0';
} else if(c >= 'A' && c <= 'Z') {
value = c - 'A';
checksum = (checksum * 10 + value / 10 + 1) % 97;
value %= 10;
} else if(c >= 'a' && c <= 'z') {
value = c - 'a';
checksum = (checksum * 10 + value / 10 + 1) % 97;
value %= 10;
} else throw new InvalidOperationException();
checksum = (checksum * 10 + value) % 97;
}
return checksum == 1;
}
@jhgbrt
Copy link

jhgbrt commented Jan 7, 2017

Nice work, but fails when IBAN contains spaces, e.g. 'GB82 WEST 1234 5698 7654 32'. In my fork I fixed this the 'brute force' way, by replacing all spaces with empty string, probably a faster method is possible

@jhgbrt
Copy link

jhgbrt commented Jan 7, 2017

The better fix is to increment the shift (initially 4) when a space is encountered.

@DvdKhl
Copy link
Author

DvdKhl commented Jan 31, 2021

Needed this one again.
I've fixed the error mentioned by jhgbrt.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment