RSA Digital Signature System is failing for larger Prime numbers - rsa

I implemented RSA cryptosystem to create a simple digital signature system. It is for freeCodeCamp's upcoming Cryptography curriculum.
The below program logs "Failure" when I use some bigger prime numbers like p = 11, q = 17. I am hashing my message and the result is smaller than N. I don't know why this is happening. Please guide me in the right direction.
This is for teaching millions of people out there. If you have any suggestions for improvement on the current implementation then please feel free to comment :)
Git Repo: https://github.com/vkweb/digital-signature-system
Thanks! Happy coding <3
const firstPrime =11;
const secondPrime = 19;
const N = firstPrime * secondPrime;
const phiOfN = (firstPrime - 1) * (secondPrime - 1);
let publicKey = 0;
function hashTheMessage(message) {
let hashValue = 0;
for (let i = 0, msgLength = message.length; i < msgLength; ++i) {
hashValue += message.charCodeAt(i);
}
return hashValue % N === 0 ? 1 : hashValue % N;
}
function isCoPrime(smallerNum, largerNum) {
for (let i = 2; i <= smallerNum; ++i) {
if (smallerNum % i === 0 && largerNum % i === 0) {
return false;
}
}
return true;
}
function generatePrivateKey() {
for (let i = 2; i < phiOfN; ++i) {
if (isCoPrime(i, N) && isCoPrime(i, phiOfN)) {
return i;
}
}
console.log("\nPrivate key can't be generated.");
return 0;
}
function generatePublicKey(privateKey) {
if (!privateKey) {
console.log("\nPublic key can't be generated.");
} else {
publicKey = 1;
while (privateKey) {
if ((publicKey * privateKey) % phiOfN === 1 && privateKey !== publicKey) {
return;
}
publicKey += 1;
}
}
}
function generateSignature(hashValue, privateKey) {
return Math.pow(hashValue, privateKey) % N;
}
function decryptSignature(digitalSignature) {
return Math.pow(digitalSignature, publicKey) % N;
}
let hashValue = hashTheMessage("Hello world!");
let privateKey = generatePrivateKey();
generatePublicKey(privateKey);
let signature = generateSignature(hashValue, privateKey);
let decryptedSignature = decryptSignature(signature);
if(decryptedSignature === hashValue)
{
console.log("Success!");
}
else
{
console.log("Failure!");
}
```

Related

In Flutter and if the number after decimal point is equal 0 convert the number to int

This is a function if the endValueFixed is equal for example 12.0 I want to print the number without zero so I want it to be 12.
void calculateIncrease() {
setState(() {
primerResult = (startingValue * percentage) / 100;
endValue = startingValue + primerResult;
endValueFixe`enter code here`d = roundDouble(endValue, 2);
});
}
This may be an overkill but it works exactly as you wish:
void main() {
// This is your double value
final end = 98.04;
String intPart = "";
String doublePart = "";
int j = 0;
for (int i = 0; i < end.toString().length; i++) {
if (end.toString()[i] != '.') {
intPart += end.toString()[i];
} else {
j = i + 1;
break;
}
}
for (int l = j; l < end.toString().length; l++) {
doublePart += end.toString()[l];
}
if (doublePart[0] == "0" && doublePart[1] != "0") {
print(end);
} else {
print(end.toString());
}
}
You may use this code as a function and send whatever value to end.
if (endValueFixed==12) {
print('${endValueFixed.toInt()}');
}
conditionally cast it to an int and print it then :)

How do I properly implement my mutation function?

I am implementing a simple genetic algorithm and everything works fine but I found that something is going wrong with the mutation function. I set the weights and biases of the agent's neural network to be identical to the fittest agent in the generation and then applied a mutation but all the agents are moving identically.
You can run my web app for yourself on this online p5 editor sketch: https://editor.p5js.org/aideveloper/sketches/Ot-SA1ulw
Can someone please help me understand what my mutation function is doing wrong?
agent.js:
class Agent {
constructor(args) {
this.x = args.x
this.y = args.y
this.color = args.color
this.weights = []
this.biases = []
this.lost = false
for(let i = 0; i < args.layers.length-1; i++)
this.weights.push([...new Array(args.layers[i+1])].map(() => [...new Array(args.layers[i])].map(() => random(-1, 1))))
for(let i = 0; i < args.layers.length-1; i++)
this.biases.push([...new Array(args.layers[i+1])].map(() => random(-1, 1)))
}
predict(x) {
let y = x
for(let i = 0; i < this.weights.length; i++) {
let hidden = [...new Array(this.weights[i].length)]
for(let j = 0; j < this.weights[i].length; j++) {
hidden[j] = 0
for(let k = 0; k < this.weights[i][j].length; k++)
hidden[j] += this.weights[i][j][k] * y[k]
hidden[j] += this.biases[i][j]
hidden[j] = 1 / (1 + Math.exp(-hidden[j]))
}
y = hidden
}
return y
}
mutate(rate=0.1) {
for(let i = 0; i < this.weights.length; i++) {
for(let j = 0; j < this.weights[i].length; j++) {
if(Math.random() < rate)
this.biases[i][j] += random(-1, 1)
for(let k = 0; k < this.weights[i][j].length; k++) {
if (Math.random() < rate)
this.weights[i][j][k] += random(-1, 1)
}
}
}
}
}
sketch.js:
const speed = 5
const n = 2000
let fittest_agent = null
let agents = []
let generation = 1
function setup() {
createCanvas(window.innerWidth, window.innerHeight)
for (let i = 0; i < n; i++) {
agents.push(new Agent({
x: 20,
y: window.innerHeight/2,
color: color(
Math.random() * 255,
Math.random() * 255,
Math.random() * 255
),
layers: [2, 10, 10, 1]
}))
}
fittest_agent = agents[0]
document.querySelector('#controls button').addEventListener('click', () => {
reproduce()
generation += 1
document.querySelector('#controls h1').textContent = `Generation: #${generation}`
})
}
function draw() {
noStroke()
background(255)
for (let i = 0; i < n; i++) {
fill(agents[i].color)
ellipse(agents[i].x, agents[i].y, 30, 30)
if(!agents[i].lost) {
let a = agents[i].predict([agents[i].x, agents[i].y])
agents[i].x += speed * cos(a * 100000)
agents[i].y += speed * sin(a * 100000)
}
fittest_agent = agents[i].x > fittest_agent.x ? agents[i] : fittest_agent
document.querySelector('#controls div').outerHTML = `<div id="fittest" style="background-color:rgb(${fittest_agent.color.levels[0]},${fittest_agent.color.levels[1]},${fittest_agent.color.levels[2]})"></div>`
document.querySelector('#controls span').textContent = Math.ceil(fittest_agent.x)
if(agents[i].x+15>window.innerWidth/4 && agents[i].x-15<window.innerWidth/4+30 && agents[i].y-15<window.innerHeight*2/3)
agents[i].lost = true
if(agents[i].x+15>window.innerWidth/2 && agents[i].x-15<window.innerWidth/2+30 && agents[i].y+15>window.innerHeight/3)
agents[i].lost = true
if(agents[i].x+15>window.innerWidth*3/4 && agents[i].x+15<window.innerWidth*3/4+30 && agents[i].y-15<window.innerHeight*2/3)
agents[i].lost = true
if(agents[i].x<15)
agents[i].lost = true
if(agents[i].y<15)
agents[i].lost = true
if(agents[i].x+15>window.innerWidth)
agents[i].lost = true
if(agents[i].y+15>window.innerHeight)
agents[i].lost = true
}
fill(135, 206, 235)
rect(window.innerWidth/4, 0, 30, window.innerHeight*2/3)
rect(window.innerWidth/2, window.innerHeight/3, 30, window.innerHeight*2/3)
rect(window.innerWidth*3/4, 0, 30, window.innerHeight*2/3)
}
function reproduce() {
agents.map(agent => {
agent.x = 20
agent.y = window.innerHeight/2
agent.lost = false
agent.weights = fittest_agent.weights
agent.biases = fittest_agent.biases
agent.color = color(random() * 255, random() * 255, random() * 255)
agent.mutate()
return agent
})
}
This is a visual representation of the issue:
The problem is in reproduce() function - you assign a reference to fittest agent's weights/biases array to new agent's weights/biases and all agents finally have same "brain". You should create a deep copy of fittest agent's weights/biases first and then assign it to agent.
function reproduce() {
agents.map(agent => {
// other code
agent.weights = deepCopy(fittest_agent.weights)
agent.biases = deepCopy(fittest_agent.biases)
// other code
}
}
function deepCopy(arr) {
// your implementation
}
You can use for ex. cloneDeep from lodash library.

Need to update the Date format on my Google Mail Script

I'm creating a Gmail script that includes 5 variables, one of which is a due date. I just want it to populate as MM/DD/YYYY, however, it is currently populating as Thu Sep 13 2018 00:00:00 GMT-0400 (EDT).
Is there a way I can do that? I've pasted my code below for your reference. Any assistance is much appreciated.
function getRowsData(sheet, range, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
var numColumns = range.getEndColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(range.getValues(), normalizeHeaders(headers));
}
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum(letter)) {
continue;
}
if (key.length == 0 && isDigit(letter)) {
continue;
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
function isDigit(char) {
return char >= '0' && char <= '9';

How to determine if a string can be manipulated to be rewritten as a palindrome?

I believe this can be achieved by counting the instances for each character in that string. Even if a single character in that string is repeated at least twice, we can declare that string as a palindrome.
For example: bbcccc can be rewritten as bccccb or ccbbcc.
edified can be rewritten as deified.
Some book mentioned we should be using hash table. I think we can just use a list and check for the character count.
Do you think the logic is correct?
Yes, the main idea is to count the times of each char existing in the string. And it will be true if the string has at most one char occurs odd times and all others even times.
For example:
aabbcc => acbbca
aabcc => acbca
aabbb => abbba
No. You don't have to use a hash map (as some of the other answers suggest). But the efficiency of the solution will be determined by the algorithm you use.
Here is a solution that only tracks odd characters. If we get 2 odds, we know it can't be a scrambled palindrome. I use an array to track the odd count. I reuse the array index 0 over and over until I find an odd. Then I use array index 1. If I find 2 odds, return false!
Solution without a hash map in javascript:
function isScrambledPalindrome(input) {
// TODO: Add error handling code.
var a = input.split("").sort();
var char, nextChar = "";
var charCount = [ 0 ];
var charIdx = 0;
for ( var i = 0; i < a.length; ++i) {
char = a[i];
nextChar = a[i + 1] || "";
charCount[charIdx]++;
if (char !== nextChar) {
if (charCount[charIdx] % 2 === 1) {
if (charCount.length > 1) {
// A scrambled palindrome can only have 1 odd char count.
return false;
}
charIdx = 1;
charCount.push(0);
} else if (charCount[charIdx] % 2 === 0) {
charCount[charIdx] = 0;
}
}
}
return true;
}
console.log("abc: " + isScrambledPalindrome("abc")); // false
console.log("aabbcd: " + isScrambledPalindrome("aabbcd")); // false
console.log("aabbb: " + isScrambledPalindrome("aabbb")); // true
console.log("a: " + isScrambledPalindrome("a")); // true
Using a hash map, I found a cool way to only track the odd character counts and still determine the answer.
Fun javascript hash map solution:
function isScrambledPalindrome( input ) {
var chars = {};
input.split("").forEach(function(char) {
if (chars[char]) {
delete chars[char]
} else {
chars[char] = "odd" }
});
return (Object.keys(chars).length <= 1);
}
isScrambledPalindrome("aba"); // true
isScrambledPalindrome("abba"); // true
isScrambledPalindrome("abca"); // false
Any string can be palindrome only if at most one character occur odd no. of times and all other characters must occur even number of times.
The following program can be used to check whether a palindrome can be string or not.
vector<int> vec(256,0); //Vector for all ASCII characters present.
for(int i=0;i<s.length();++i)
{
vec[s[i]-'a']++;
}
int odd_count=0,flag=0;
for(int i=0;i<vec.size();++i)
{
if(vec[i]%2!=0)
odd_count++;
if(odd_count>1)
{
flag=1;
cout<<"Can't be palindrome"<<endl;
break;
}
}
if(flag==0)
cout<<"Yes can be palindrome"<<endl;
My code check if can it is palindrome or can be manipulated to Palindrome
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
//Tested on windows 64 bit arhc by using cygwin64 and GCC
bool isPalindrome (char *text);
int main()
{
char text[100]; // it could be N with defining N
bool isPal,isPosPal = false;
printf("Give me a string to test if it is Anagram of Palindrome\n");
gets(text);
isPal = isPalindrome(text);
isPosPal = isAnagramOfPalindrome(text);
if(isPal == false)
{
printf("Not a palindrome.\n");
}
else
{
printf("Palindrome.\n");
}
if(isPosPal == false)
{
printf("Not Anagram of Palindrome\n");
}
else
{
printf("Anagram of Palindrome\n");
}
return 0;
}
bool isPalindrome (char *text) {
int begin, middle, end, length = 0;
length = getLength(text);
end = length - 1;
middle = length/2;
for (begin = 0; begin < middle; begin++)
{
if (text[begin] != text[end])
{
return false;
}
end--;
}
if (begin == middle)
return true;
}
int getLength (char *text) {
int length = 0;
while (text[length] != '\0')
length++;
printf("length: %d\n",length);
return length;
}
int isAnagramOfPalindrome (char *text) {
int length = getLength(text);
int i = 0,j=0;
bool arr[26] = {false};
int counter = 0;
//char string[100]="neveroddoreven";
int a;
for (i = 0; i < length; i++)
{
a = text[i];
a = a-97;
if(arr[a])
{
arr[a] = false;
}
else
{
arr[a] = true;
}
}
for(j = 0; j < 27 ; j++)
{
if (arr[a] == true)
{
counter++;
}
}
printf("counter: %d\n",counter);
if(counter > 1)
{
return false;
}
else if(counter == 1)
{
if(length % 2 == 0)
return false;
else
return true;
}
else if(counter == 0)
{
return true;
}
}
as others have posted, the idea is to have each character occur an even number of times for an even length string, and one character an odd number of times for an odd length string.
The reason the books suggest using a hash table is due to execution time. It is an O(1) operation to insert into / retrieve from a hash map. Yes a list can be used but the execution time will be slightly slower as the sorting of the list will be O(N log N) time.
Pseudo code for a list implementation would be:
sortedList = unsortedList.sort;
bool oddCharFound = false;
//if language does not permit nullable char then initialise
//current char to first element, initialise count to 1 and loop from i=1
currentChar = null;
currentCharCount = 0;
for (int i=0; i <= sortedList.Length; i++) //start from first element go one past end of list
{
if(i == sortedList.Length
|| sortedList[i] != currentChar)
{
if(currentCharCount % 2 = 1)
{
//check if breaks rule
if((sortedList.Length % 2 = 1 && oddCharFound)
|| oddCharFound)
{
return false;
}
else
{
oddCharFound = true;
}
}
if(i!= sortedList.Length)
{
currentCharCount = 1;
currentChar = sortedList[i];
}
}
else
{
currentCharCount++;
}
}
return true;
Here is a simple solution using an array; no sort needed
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[256] = { 0 };
unsigned char i[] = {"aaBcBccc"};
unsigned char *p = &i[0];
int c = 0;
int j;
int flag = 0;
while (*p != 0)
{
a[*p]++;
p++;
}
for(j=0; j<256; j++)
{
if(a[j] & 1)
{
c++;
if(c > 1)
{
flag = 1;
break;
}
}
}
if(flag)
printf("Nope\n");
else
printf("yup\n");
return 0;
}
C#:
bool ok = s.GroupBy(c => c).Select(g => g.Count()).Where(c => c == 1).Count() < 2;
This solution, however, does use hashing.
Assuming all input characters are lower case letters.
#include<stdio.h>
int main(){
char *str;
char arr[27];
int j;
int a;
j = 0;
printf("Enter the string : ");
scanf("%s", str);
while (*str != '\0'){
a = *str;
a = a%27;
if(arr[a] == *str){
arr[a]=0;
j--;
}else{
arr[a] = *str;
j++;
}
*str++;
}
if(j==0 || j== -1 || j==1){
printf ("\nThe string can be a palindrome\n");
}
}

Stochastic universal sampling

I need a sus implementation in c# for finding candidate individuals in a population this is what i have so far but im not sure if it is correct.
public void sus(IEnumerable<TimeTable>population)
{
var ag = population.Sum(i => normalize((double) i.Fitness, true));
var mark = rnMutate.NextDouble();
var index = 0;
foreach (var candidate in population)
{
var cu = population.Sum(i => normalize((double)i.Fitness, false)) / ag * 5;
while (cu > mark + index)
{
Survivors.Add(candidate);
index++;
}
}
}
public double normalize(double fitness, bool natural)
{
if (natural)
return fitness;
return fitness == (double)FitnessLBound ? double.PositiveInfinity : 1 / fitness;
}
private IEnumerable<TimeTable> StochasticSample(IEnumerable<TimeTable> population, int size)
{
var t = population.Sum(it => it.Fitness);
var temp = new List<TimeTable>();
var ptr = rnMutate.NextDouble();
var sum = 0M;
for (int i = 0; i < size; i++)
{
for (sum += ExpValue(i, t); sum > (decimal) ptr; ptr++)
{
temp.Add(population.ElementAt(i));
--size;
}
}
return temp;
}
private decimal ExpValue(decimal fitness, decimal sum)
{
return decimal.Divide(fitness, sum);
}