How to solve this Range Error in my code? - encryption

I'm trying to create an cipher app on android studio using flutter. Right now I'm working on a simple Atbash Cipher, but I get a range error when trying to test it. These are the encrypt and decrypt codes:
#override
String encrypt(String plaintext, {String key}) {
String alfa = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String alfaReverso = "";
for(int i = alfa.length-1; i > -1; i++){
alfaReverso += alfa[i];
}
String encryText = "";
for (int i = 0; i < plaintext.length; i++){
if(plaintext.codeUnitAt(i) == 32){
encryText += " ";
}
else{
int count = 0;
for(int j = 0; j < alfa.length; j++){
if(plaintext[i] == alfa[j]){
encryText += alfaReverso[j];
break;
}
}
}
}
return "ENCRYPT Plain = " + encryText;
}
}
#override
String decrypt(String cyphertext, {String key}) {
String alfa = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String alfaReverso = "";
for(int i = alfa.length-1; i > -1; i++){
alfaReverso += alfa[i];
}
String dencryText = "";
for (int i = 0; i < cyphertext.length; i++){
if(cyphertext.codeUnitAt(i) == 32){
dencryText += " ";
}
else{
int count = 0;
for(int j = 0; j < alfaReverso.length; j++){
if(cyphertext[i] == alfaReverso[j]){
dencryText += alfa[j];
break;
}
}
}
}
return "ENCRYPT Plain = " + dencryText;
}
When trying to run it this is the range exception I get:
I/flutter ( 6004): RangeError (index): Invalid value: Not in range 0..25, inclusive: 26
I know it has something to do with the alphabetI'm using, but I don't know how to solve it.

There is an error when you start from the highest index:
for(int i = alfa.length-1
Your index has to go down and you are using ++.
Use this:
for(int i = alfa.length-1; i > -1; i--)

Related

How to convert Ximea xiAPI camera data into QImage?

I have data from a camera in mono 8bit.
This is converted into an int vector using
std::vector<int> grayVector(size);
// convert / copy pointer data into vector: 8 bit
if (static_cast<XI_IMG_FORMAT>(format) == XI_MONO8)
{
quint8* imageIterator = reinterpret_cast<quint8*> (pMemVoid);
for (size_t count = 0; count < size; ++count)
{
grayVector[count] = static_cast<int>(*imageIterator);
imageIterator++;
}
}
Next, I need to convert this into a QImage. If I set the image format to QImage::Format_Mono the app crashes. With QImage::Format_RGB16 I get strippes, and with QImage::Format_RGB32 everything is black.
I would like to know how to do this the best, efficient and correct way?
// convert gray values into QImage data
QImage image = QImage(static_cast<int>(sizeX), static_cat<int>(sizeY), QImage::Format_RGB16);
for ( int y = 0; y < sizeY; ++y )
{
int yoffset = sizeY*y;
QRgb *line = reinterpret_cast<QRgb *>(image.scanLine(y)) ;
for ( int x = 0; x < sizeX ; ++x )
{
int pos = x + yoffset;
int color = grayVector[static_cast<size_t>(pos)];
*line++ = qRgb(color, color, color);
}
}
The conversion to int is unnecessary and you do it in a very inefficient way; all you need is to use the QImage::Format_Grayscale8 available since Qt 5.5 (mid-2015).
Anyway, what you really want is a way to go from XI_IMG to QImage. The default BP_UNSAFE buffering policy should be adequate - the QImage will do a format conversion, so taking the data from XiApi's internal buffer is OK. Thus the following - all of the conversions are implemented in Qt and are quite efficient - much better than most any naive code.
I didn't check whether some Xi formats may need a BGR swap. If so, then the swap can be set to true in the format selection code and the rest will happen automatically.
See also: xiAPI manual.
static QVector<QRgb> grayScaleColorTable() {
static QVector<QRgb> table;
if (table.isEmpty()) {
table.resize(256);
auto *data = table.data();
for (int i = 0; i < table.size(); ++i)
data[i] = qRgb(i, i, i);
}
return table;
}
constexpr QImage::Format grayScaleFormat() {
return (QT_VERSION >= QT_VERSION_CHECK(5,5,0))
? QImage::Format_Grayscale8
: QImage::Format_Indexed8;
}
QImage convertToImage(const XI_IMG *src, QImage::Format f) {
Q_ASSERT(src->fmt == XI_MONO16);
Q_ASSERT((src->padding_x % 2) == 0);
if (src->fmt != XI_MONO16) return {};
const quint16 *s = static_cast<const quint16*>(src->bp);
const int s_pad = src->padding_x/2;
if (f == QImage::Format_BGR30 ||
f == QImage::Format_A2BGR30_Premultiplied ||
f == QImage::Format_RGB30 ||
f == QImage::Format_A2RGB30_Premultiplied)
{
QImage ret{src->width, src->height, f};
Q_ASSERT((ret->bytesPerLine() % 4) == 0);
const int d_pad = ret->bytesPerLine()/4 - ret->width();
quint32 *d = (quint32*)ret.bits();
if (s_pad == d_pad) {
const int N = (src->width + s_pad) * src->height - s_pad;
for (int i = 0; i < N; ++i) {
quint32 const v = (*s++) >> (16-10);
*d++ = 0xC0000000 | v << 20 | v << 10 | v;
}
} else {
for (int j = 0; j < src->height; ++j) {
for (int i = 0; i < src->width; ++i) {
quint32 const v = (*s++) >> (16-10);
*d++ = 0xC0000000u | v << 20 | v << 10 | v;
}
s += s_pad;
d += d_pad;
}
}
return ret;
}
QImage ret{src->width, src->height, grayScaleFormat()};
const int d_pad = ret->bytesPerLine() - ret->width();
auto *d = ret.bits();
if (s_pad == d_pad) {
const int N = (src->width + s_pad) * src->height - s_pad;
for (int i = 0; i < N; ++i) {
*d++ = (*s++) >> 8;
} else {
for (int j = 0; j < src->height; ++j) {
for (int i = 0; i < src->width; ++i)
*d++ = (*s++) >> 8;
s += s_pad;
d += d_pad;
}
}
return ret;
}
QImage fromXiImg(const XI_IMG *src, QImage::Format dstFormat = QImage::Format_ARGB32Premultiplied) {
Q_ASSERT(src->width > 0 && src->height > 0 && src->padding_x >= 0 && src->bp_size > 0);
Q_ASSERT(dstFormat != QImage::Format_Invalid);
bool swap = false;
int srcPixelBytes = 0;
bool externalConvert = false;
QImage::Format srcFormat = QImage::Format_Invalid;
switch (src->fmt) {
case XI_MONO8:
srcPixelBytes = 1;
srcFormat = grayScaleFormat();
break;
case XI_MONO16:
srcPixelBytes = 2;
externalConvert = true;
break;
case XI_RGB24:
srcPixelBytes = 3;
srcFormat = QImage::Format_RGB888;
break;
case XI_RGB32:
srcPixelBytes = 4;
srcFormat = QImage::Format_RGB32;
break;
};
if (srcFormat == QImage::Format_Invalid && !externalConvert) {
qWarning("Unhandled XI_IMG image format");
return {};
}
Q_ASSERT(srcPixelBytes > 0 && srcPixelBytes <= 4);
int bytesPerLine = src->width * srcPixelBytes + src->padding_x;
if ((bytesPerLine * src->height - src->padding_x) > src->bp_size) {
qWarning("Inconsistent XI_IMG data");
return {};
}
QImage ret;
if (!externalConvert)
ret = QImage{static_cast<const uchar*>(src->bp), src->width, src->height,
bytesPerLine, srcFormat};
else
ret = convertToImage(src, dstFormat);
if (ret.format() == QImage::Format_Indexed8)
ret.setColorTable(grayScaleColorTable());
if (ret.format() != dstFormat)
ret = std::move(ret).convertToFormat(dstFormat);
if (swap)
ret = std::move(ret).rgbSwapped();
if (!ret.isDetached()) // ensure that we don't share XI_IMG's data buffer
ret.detach();
return ret;
}

Alternative to System.Web.Security.Membership.GeneratePassword in aspnetcore (netcoreapp1.0)

Is there any alternative to System.Web.Security.Membership.GeneratePassword in AspNetCore (netcoreapp1.0).
The easiest way would be to just use a Guid.NewGuid().ToString("n") which is long enough to be worthy of a password but it's not fully random.
Here's a class/method, based on the source of Membership.GeneratePassword of that works on .NET Core:
public static class Password
{
private static readonly char[] Punctuations = "!##$%^&*()_-+=[{]};:>|./?".ToCharArray();
public static string Generate(int length, int numberOfNonAlphanumericCharacters)
{
if (length < 1 || length > 128)
{
throw new ArgumentException(nameof(length));
}
if (numberOfNonAlphanumericCharacters > length || numberOfNonAlphanumericCharacters < 0)
{
throw new ArgumentException(nameof(numberOfNonAlphanumericCharacters));
}
using (var rng = RandomNumberGenerator.Create())
{
var byteBuffer = new byte[length];
rng.GetBytes(byteBuffer);
var count = 0;
var characterBuffer = new char[length];
for (var iter = 0; iter < length; iter++)
{
var i = byteBuffer[iter] % 87;
if (i < 10)
{
characterBuffer[iter] = (char)('0' + i);
}
else if (i < 36)
{
characterBuffer[iter] = (char)('A' + i - 10);
}
else if (i < 62)
{
characterBuffer[iter] = (char)('a' + i - 36);
}
else
{
characterBuffer[iter] = Punctuations[i - 62];
count++;
}
}
if (count >= numberOfNonAlphanumericCharacters)
{
return new string(characterBuffer);
}
int j;
var rand = new Random();
for (j = 0; j < numberOfNonAlphanumericCharacters - count; j++)
{
int k;
do
{
k = rand.Next(0, length);
}
while (!char.IsLetterOrDigit(characterBuffer[k]));
characterBuffer[k] = Punctuations[rand.Next(0, Punctuations.Length)];
}
return new string(characterBuffer);
}
}
}
I've omitted the do...while loop over the CrossSiteScriptingValidation.IsDangerousString. You can add that back in yourself if you need it.
You use it like this:
var password = Password.Generate(32, 12);
Also, make sure you reference System.Security.Cryptography.Algorithms.
System.Random doesn't provide enough entropy when used for security reasons.
https://cwe.mitre.org/data/definitions/331.html
Why use the C# class System.Random at all instead of System.Security.Cryptography.RandomNumberGenerator?
Please see the example below for a more secure version of #khellang version
public static class Password
{
private static readonly char[] Punctuations = "!##$%^&*()_-+[{]}:>|/?".ToCharArray();
public static string Generate(int length, int numberOfNonAlphanumericCharacters)
{
if (length < 1 || length > 128)
{
throw new ArgumentException("length");
}
if (numberOfNonAlphanumericCharacters > length || numberOfNonAlphanumericCharacters < 0)
{
throw new ArgumentException("numberOfNonAlphanumericCharacters");
}
using (var rng = RandomNumberGenerator.Create())
{
var byteBuffer = new byte[length];
rng.GetBytes(byteBuffer);
var count = 0;
var characterBuffer = new char[length];
for (var iter = 0; iter < length; iter++)
{
var i = byteBuffer[iter] % 87;
if (i < 10)
{
characterBuffer[iter] = (char)('0' + i);
}
else if (i < 36)
{
characterBuffer[iter] = (char)('A' + i - 10);
}
else if (i < 62)
{
characterBuffer[iter] = (char)('a' + i - 36);
}
else
{
characterBuffer[iter] = Punctuations[GetRandomInt(rng, Punctuations.Length)];
count++;
}
}
if (count >= numberOfNonAlphanumericCharacters)
{
return new string(characterBuffer);
}
int j;
for (j = 0; j < numberOfNonAlphanumericCharacters - count; j++)
{
int k;
do
{
k = GetRandomInt(rng, length);
}
while (!char.IsLetterOrDigit(characterBuffer[k]));
characterBuffer[k] = Punctuations[GetRandomInt(rng, Punctuations.Length)];
}
return new string(characterBuffer);
}
}
private static int GetRandomInt(RandomNumberGenerator randomGenerator)
{
var buffer = new byte[4];
randomGenerator.GetBytes(buffer);
return BitConverter.ToInt32(buffer);
}
private static int GetRandomInt(RandomNumberGenerator randomGenerator, int maxInput)
{
return Math.Abs(GetRandomInt(randomGenerator) % maxInput);
}
}

Runtime error SIGSEGV on SPOJ

I'm trying to solve problem ARDA1 - The hunt for Gollum on SPOJ
Here's the link: http://www.spoj.com/problems/ARDA1/
And here's my code:
#include <algorithm>
#include <string>
using namespace std;
string map[2010];
string marshes[310];
char str[310];
int main()
{
int N1, N2, M1, M2 = 0;
freopen("INPUT.txt","rt",stdin);
scanf("%d%d", &N1, &N2);
for (int i = 0; i < N1; i++) {
scanf("%s", &str);
marshes[i] = str;
}
scanf("%d%d", &M1, &M2);
for (int i = 0; i < M1; i++) {
scanf("%s", &str);
map[i] = str;
}
bool isFound = false;
for (int i = 0; i <= M1 - N1; i++)
for (int j = 0; j <= M2 - N2; j++) {
if (map[i][j] == marshes[0][0]) {
bool isSame = true;
for (int t = 0; t < N1; t++) {
if (marshes[t] != map[i+t].substr(j, N2)) {
isSame = false;
break;
}
}
if (isSame) {
printf("(%d,%d)\n", i+1, j+1);
isFound = true;
}
}
}
if (!isFound)
printf("NO MATCH FOUND...");
return 0;
}
But I got "Runtime error (SIGSEGV)" when I submit my solution. I know that we get SIGSEGV when trying to access elements out of bound or when there's not enough memory.
I checked my code but couldn't find anything wrong and it worked on my computer. Anyone can tell me what could be wrong here?

Array only printing one number

I am having trouble printing my array in a asp:Label. the array is 5 numbers long, but it will only print out one of the numbers when I do the id.Text = arrayname;
Here is the method:
void random4helper()
{
Random rand = new Random();
int min = 1;
int max = 51;
int randomNum;
int i = 0;
int count = 0;
bool loop = true;
while (loop)
{
randomNum = rand.Next(min, max);
if (!meganumbers4.Contains(randomNum))
{
meganumbers4[i] = randomNum;
count += 1;
i += 1;
}
if (count == 5)
{
loop = false;
}
}
for (int j = 0; j < meganumbers4.Length; j++)
{
d.Text = meganumbers4[j] + " ";
}
}
Here is the corresponding Label:
<asp:Label runat="server" id="a" CssClass="print" Text="A"></asp:Label>
You are overwriting the value in each loop. Instead, you need to add the new value to the current value. Change this line:
d.Text = meganumbers4[j] + " ";
To:
d.Text += meganumbers4[j] + " ";

Create 2 or more text files with ASP.NET

I have created a web app which creates 1 text file. Inside this text file it is created 1000 rows with the same word "TRY AGAIN". After this each 50 rows I put a random code which means in 1000 rows, 20 rows are random.
This is my code:
static Random randNum = new Random();
public static string Random(int ran)
{
string _charachters = "ABCDEFGHIJKMLNOPQRSTUVWXYZ0123456789";
char[] chars = new char[ran];
int allowedCharCount = _charachters.Length;
for (int i = 0; i < ran; i++)
{
chars[i] = _charachters[(int)((_charachters.Length) * randNum.NextDouble())];
}
return new string(chars);
}
protected void Button1_Click(object sender, EventArgs e)
{
string pathCreate = #"C:\" + TextBox3.Text + ".txt";
if (!File.Exists(pathCreate))
{
using (StreamWriter sw = File.CreateText(pathCreate))
{
for (int i = 1; i <= int.Parse(TextBox1.Text); i++)
{
sw.WriteLine("TRY AGAIN.");
}
}
}
string pathRandom = #"C:\" + TextBox3.Text + ".txt";
string[] lines = File.ReadAllLines(pathRandom);
for (int i = 0; i < lines.Length; i += int.Parse(TextBox2.Text))
{
lines[i] = lines[i].Replace("TRY AGAIN.", Random(int.Parse("7")));
}
File.WriteAllLines(pathRandom, lines);
}
Now I want to create 2 ore more text files with one click of a button. And on each text file there will be random codes (not duplicates). Any idea?
Thank You.
I found the solution. It is late in my country and my brain barely works. :P
for(int j = 1; j <= 10; j++)
{
string pathKrijo = #"C:\inetpub\wwwroot\KODET\" + j.ToString() + ".txt";
using (StreamWriter sw = File.CreateText(pathKrijo))
{
for (int i = 1; i <= 100; i++)
{
sw.WriteLine("Provo Përsëri.");
}
}
string pathKodFitues = #"C:\inetpub\wwwroot\KODET\" + j.ToString() + ".txt";
string[] lines = File.ReadAllLines(pathKodFitues);
for (int i = 0; i < lines.Length; i += 10)
{
lines[i] = lines[i].Replace("Provo Përsëri.", Random(int.Parse("7")));
}
File.WriteAllLines(pathKodFitues, lines);
}

Resources