0% found this document useful (0 votes)
10 views10 pages

Python String Encryption Techniques

The document outlines a series of exercises related to cryptography and password strength assessment using Python programming. Each exercise presents a specific task, such as encrypting strings, calculating password strength, determining happy numbers, and generating sequences based on defined rules. The document includes example inputs and expected outputs, as well as Python function definitions for implementing the required functionalities.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views10 pages

Python String Encryption Techniques

The document outlines a series of exercises related to cryptography and password strength assessment using Python programming. Each exercise presents a specific task, such as encrypting strings, calculating password strength, determining happy numbers, and generating sequences based on defined rules. The document includes example inputs and expected outputs, as well as Python function definitions for implementing the required functionalities.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Exercise 1

We want to encrypt a given string CH whose size does not exceed 50.
characters in a string result Res as follows: traverse the string CH
from left to right counting the number of successive occurrences of each
character of the string CH, then to sort the string Res, this number followed by the character e
question.
Write a Python program that allows the input of the string CH which must be non-empty.
and formed solely by alphabetical letters, then to create and display the
Res chain according to the principle described above.
Example

If CH='aaaFyBssssssssssssazz' then the string Res that will be displayed is


3a1F1y1B12s1a2z

def crypter(CH):
res =''
if len(CH) <= 50:
cpt = 1
for i in range(len(CH)-1):
if CH[i] == CH[i+1]:
cpt += 1
else:
res += str(cpt) + CH[i]
cpt = 1
res += str(cpt) + CH[-1]
return res

print(crypter("aaaFyBssssssssssssazz"))

Exercise 2
We propose to write a program that allows entering and encrypting a word M.
not seen, composed only of uppercase letters and to display the encrypted word
MC.
The encryption method is as follows:
For each letter, determine its number of occurrences.
(appearing in the word M. Determine K which is equal to 2*n*sin is odd
and will be equal to (n DIV 2) is even. Replace each letter with Kth
letter that follows it in the interval of the alphabet ['A'...'Z']. For the last ones
letters, we return from the beginning, for example if K=3, we will replace 'A' with
'D' becomes 'E', 'C' becomes 'E'... 'Y' becomes 'B' and 'Z' becomes 'C'.
Example

For the word 'HAPPY'


The encrypted word will be: 'JCQQA'
Write a Python program that allows entering a non-empty and compound word.
only in uppercase letters, then display the encrypted word according to the principle
described above.
def crypter_mc(s):
alpha ='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
res =''
for letter in s:
occurence = [Link](lettre)
pos = 0
if occurrence % 2 == 0:
pos = occurrence // 2
else:
pos = occurrence * 2
order = [Link](letter)
index = position + order
if > 25
index = index % 26
res += alpha[index]
return res

print(crypter_mc("HAPPY"))

Exercise 3

One of the oldest cryptographic systems (easily decipherable) consists of shifting the
letters of a message to render it unreadable. Thus, A becomes B, B becomes C, etc. And
the Z become A
Example

If CH='ABCCZABEY' then the encrypted string that will be displayed is


BCDDABCEZ
Write a program that asks a string CH from the user and encodes it in a
Res chain according to this principle.

def crypter(ch):
alpha ='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
res =''
for character in ch:
index = [Link](character)
pos = index + 1
if pos == 26:
pos = 0
res += alpha[pos]
return res

print(crypter("ABCCZABEY"))

Exercise 4
A (relative) improvement of the principle used in exercise 3 consists of operating with
shift not by 1, but by any number of letters. Thus, for example, if
if we choose a shift of 3, A becomes E, B becomes E, etc. And Z
become C
Create a python program based on the same principle as the previous one, but that
request additionally what is the offset to use.
def cesar(s, d):
alpha ='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
res =''
for letter in s:
order = [Link](letter)
index = order + d
if index > 25:
index = index % 26
res += alpha[index]
return res

print(cesar("ABCDEFGH", 3))

Exercise 5

A later technique of cryptography consisted of operating not with a shift


systematic, but by a random substitution. For this, a key alphabet is used,
in which the letters follow in a disordered manner, for example,
"HYLUJPVREAKBNDOFSQZCWMGITX" This is the key that will be used to encode afterwards
the message. According to our example, A's will become H's, B's will become Y's, C's will become L's, etc.
Example

If CH='ABCDEFZ' then the encrypted string that will be displayed is 'HYLUJPX'


Write a Python program that performs this encryption (the keyword alphabet will be input by
the user, and it is assumed that he enters a correct input) on a string of
characters CH and store the result in Res
def crypter_alea(msg):
cle ='HYLUJPVREAKBNDOFSQZCWMGITX'
alpha ='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
res =''
for character in msg:
index = [Link](character)
res += cle[indice]
return res
print(crypter_alea("ABCDEFZ"))

Exercise 6

A cryptography system much harder to break than the previous ones was
invented in the 16th century by the French Vigenère. It consisted of a combination of
different Caesar ciphers.
Indeed, we can write 25 alphabets shifted in relation to the normal alphabet:
The alphabet that starts with B and ends with ...YZA
The alphabet that starts with C and ends with ...ZAB
etc.
The encoding will be based on the principle of the Caesar cipher: we replace the letter
originally by the letter occupying the same place in the shifted alphabet.
But unlike the Caesar cipher, the same message will use not one, but
several shifted alphabets. To know which alphabets should be used, and in
what order, we use a key.
If this key is 'VIGENERE' and the message is 'We must encode this phrase', we will proceed
as follows:
The first letter of the message, I, is the 9th letter of the normal alphabet. It must be
coded using the alphabet starting with the first letter of the key, V. In this
alphabet, the 9th letter is D. I thus becomes D.
The second letter of the message, L, is the 12th letter of the normal alphabet. It must be
coded using the alphabet starting with the second letter of the key, I. In this
alphabet, the 12th letter is S. L becomes S, etc.
When we reach the last letter of the key, we start again from the first.
Write a Python program that performs Vigenère encryption, asking properly.
sure at the start the key to the user.
def Vigenere(msg, key):
alpha ='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
res =''
i=0
for character in msg:
debut = [Link](cle[i])
pos = [Link](character)
index = pos + start
if index > 25:
index -= 26
res += alpha[index]
i += 1
if i >= len(cle):
i=0
return res

It is necessary to encode this phrase.


Exercise 7
A website administrator wants to ensure maximum security for the
users of the site. To do this, he decides to create an application that assesses strength
the passwords of different users of the site, knowing that a password is
a string of characters that does not contain spaces and accented letters.
The strength of a password varies, according to the value of a calculated score, from 'Very weak'
up to 'Very strong':
If the score is <20, the password strength is 'Very Weak'
Otherwise, if the score < 40, the strength of a password is 'Weak'
Otherwise, if the score <80, the strength of the password is 'Strong'
Otherwise, the password strength is 'Very strong'
The score is calculated by adding bonuses and subtracting penalties.
The awarded bonuses are:
Total number of characters * 4
(Total number of characters - number of uppercase letters) * 2
(Total number of characters - number of lowercase letters) * 3
Number of non-alphabetic characters * 5
The penalties imposed are:
The length of the longest sequence of lowercase letters * 2
The length of the longest sequence of uppercase letters * 3
Example

For the password 'P@cSI_promo2017', the score is calculated as follows:


The sum of bous = 15*4 + (15-3) *2 + (15-6) *3 + 6*5 = 141
The total number of characters = 15
The number of uppercase letters = 3
The number of lowercase letters = 6
The number of non-alphabetic characters = 6
The sum of the penalties = 5*2+2*2=14
The length of the longest sequence of lowercase letters ('promo') = 5
The length of the longest sequence of uppercase letters ('SI') = 2
The final score = 141-14=127; since 127>80 then the password is considered
Very strong
Work requested:
1. Write a function NbCMin(pass) that returns the number of characters
lowercase.
2. Write a function NbCMaj(pass) that returns the number of characters
upper case letters.
3. Write a function NbCAlphapass() that returns the number of characters
non-alphabetic.
4. Write a function LongMaj(pass) that returns the length of the longest one.
sequence of uppercase letters.
5. Write a function LongMin(pass) that returns the length of the longest
sequence of lowercase letters.
6. Write a function score(pass) that displays the score of a password
def NbcMin(pass):
nb = 0
for I in the past:
if a <= i <='z':
nb += 1
return nb

def NbcMaj(password):
nb = 0
for i in pass
if A <= i <='Z':
nb += 1
return nb

def NbcAlpha(password):
return len(pass)-NbcMaj(pass)-NbcMin(pass)

def longMaj(password):
d=0
s=0
i=0
while i < len(passe):
if 'A' < passe[i] < 'Z':
s += 1
else:
if s > d:
d=s
s=0
i += 1

return d

def longMin(pass):
d=0
s=0
i=0
while i < len(passe):
if a if passe[i] is less than 'z':
s += 1
else:
if s > d:
d=s
s=0
i += 1

return d

def score(password):
bonus = (len(password)-NbcMin(password))*3+(len(password) -
NbcMaj(password))*2+(len(password)-NbcAlpha(password))*5
penalites = longMaj(password)*3+longMin(password)*2
val = bonus-penalties
if val < 20:
Very low
elif val < 40:
Weak
elif val < 80:
Fort
else:
Very strong

pas ="P@SI_promo2016"
score(pas)

Exercise 8
A happy number is an integer that, when you add the squares of each
of these numbers, then the squares of the numbers of this result and so on until
the obtaining of a single digit number equal to 1 (one).
Example:
N=7 is happy, since:
7 2= 49
4 2+9 2=97
9 2+ 72 = 130
1 2+ 3 2+ 0 2= 10
1 2+ 02 = 1
We arrived at a single digit number that equals 1, so N=7 is happy.

Work requested:

Write a function happy(nb) that determines if a number n is happy.


happy or not.
def heureux(nb):
etat= False# the state of the number, is it happy or not by default the
name is not happy
check if the number is less than 10
nombre= str(nb)
limite= False
while limit== False
s= 0
for iin nombre:
s+= int(i)**2
nombre= str(s)
if name== '1':
etat= True
break
if if(int(number) < 10): # if the number < 10 then limit=True
limite= True
return state

print(happy(7))
Exercise 9

The Robinson sequence is defined by:


U0=0
It is built by concatenating the number of appearances of each of the
digits constituting the term Un-1 followed by the digit itself, in order
decreasing of the numbers, for all n>0.
Example :
For n=5, U5=13123110
Indeed:
U0=0
U1=10 because there is an appearance (1) of the digit 0 in U0
U2=1110 because there is one appearance (1) of the digit 1 and one appearance (1) of the
digit 0 in U1
U3=3110 because there is an appearance (3) of the number 1 and an appearance (1) of
number 0 in U2
U4=132110 because there is one appearance (1) of the digit 3, two appearances of the digit
1 and an appearance (1) of the number 0 in U3
U5=13123110 because there is one appearance (1) of the number 3, one appearance of
number 2, three occurrences of the number 1 and one occurrence (1) of the number 0 in
U3
Work requested:

Write a function Robinson(N) to calculate the Nth term of the sequence.


robinson
def robinson(n):
U= 0
for _in range(1, n+1):
ch= str(U)
L= [0,0,0,0,0,0,0,0,0,0]
for chiffrein ch:
L[int(number)] += 1
res= ''
for jin range(9,-1,-1):
if L[j] != 0:
res+= str(L[j]) + str(j)
U= int(res)
print('Term: ', n, ' is ', U)

robinson(5)

Exercise 10
In an arithmetic context, prime factorials and
prime primordial numbers as indicated below.
A PF number is said to be a factorial prime if it satisfies the following two properties:
PF is a prime number
And PF is written in the form of a factorial increased or decreased by 1.
(PF=F! + 1 or PF=F! - 1), knowing that the factorial of F noted F! is equal to
F*(F-1) *…*1
Example

7 is a prime factorial number because 7 is prime and it is written in the form


6 + 1.
719 is a factorial prime because 719 is prime and it is written as
form 6! - 1.
A PP number is said to be a primordial prime if it satisfies the following two properties:
PP is a prime number.
PP is written in the form of a prime incremented or decremented by 1.
(PP=P#+1 or PP=P#-1), knowing that the primorial of P denoted P# is equal
to produce prime numbers less than or equal to P.
Example

211 is a prime primorial number because 211 is prime and it is written as


form 7# + 1. Indeed, 7# + 1 = 2*3*5*7 + 1 = 210 + 1 = 211
30029 is a prime primordial number because 30029 is prime and it is written
sous la forme 13# - 1. En effet, 13# - 1 = 2*3*5*7*11*13-1=30030 – 1
=30029
Requested work:
1. Write a function premier_fact(n) that allows to verify if n is
a factorial prime number or not
2. Write a function premier_primoriel(n) that checks if n
is a prime primordial number or not
def premier (n):
etat= True
for iin range(2, (n//2)+1):
if n% i== 0:
etat= False
break
return state

def first_fact(n):
etat= False
if first
f= 1
ordre= 2
while f < n:
f= f*order
order+= 1
if f+1 == nor f-1 == n:
etat= True
return state
def premier_primoriel(n):
etat= False
if first (n) True:
p= 3
s= 0
while s < n:
s= 1
for iin range(2, p+1):
if first(i)== True
s= s*i
p+= 1
if s+1 == nor s-1 == n:
etat= True
break
return state

n= 719
print(prime_fact(n))

Common questions

Powered by AI

The Vigenère cipher differs from the Caesar cipher in that it uses a series of different shift alphabets, determined by a key, to encrypt the message. Each letter of the message is encrypted using a different shifted alphabet, as dictated by the corresponding letter in the keyword. In contrast, the Caesar cipher involves shifting all characters in the plaintext by the same amount .

The encrypted values in the random substitution technique are computed by mapping each character in the original message to a character in a user-provided key alphabet. Each letter of the message corresponds to the position of its regular alphabetical occurrence, then aligns with the respective character in the key alphabet, resulting in a jumbled but consistent mapping for decryption .

A factorial prime number is defined as a prime number that can be expressed in the form of F! + 1 or F! - 1, where F! is the factorial of F. The criteria for determining factorial primality involve verifying the primality of the number and its conformity to one of the described factorial expressions. Examples include numbers like 7 and 719, which meet both conditions .

In the modified Caesar cipher, the user-defined offset determines the number of positions each character in the plaintext is shifted along the alphabet. Unlike the standard Caesar cipher, which always uses a shift of one, this method allows for customization of the shift size, thereby increasing the complexity and variety of the ciphered text .

The password strength calculation involves both bonuses and penalties. Bonuses include multiplying the total character count by 4, subtracting the number of uppercase letters from the total and multiplying by 2, subtracting the number of lowercase letters from the total and multiplying by 3, and multiplying the number of non-alphabetic characters by 5. Penalties are applied based on the length of the longest sequence of consecutive lowercase and uppercase letters, multiplied by 2 and 3 respectively. The final score determines password strength, categorized into 'Very Weak', 'Weak', 'Strong', or 'Very Strong' based on the score thresholds .

The algorithm for determining if a number is happy involves repeatedly summing the squares of its digits until a single-digit number is obtained. If this number is 1, the original number is considered happy. The process starts by converting the number into a string to iterate over each digit, then computes the sum of the squares of these digits. This result is applied recursively until either '1' is reached, indicating happiness, or it falls into a cycle that avoids '1', signifying the number is not happy .

The encryption method determines the shift key by calculating for each letter its number of occurrences in the word. If the occurrence is even, the shift is n/2 (integer division); if it's odd, the shift is n*2. This alteration leads to the replacement of each letter with the kth letter that follows it in the alphabet, wrapping around if necessary, thus creating a uniquely encrypted text .

A password score of 127 is interpreted as 'Very Strong' according to the scoring criteria, as it exceeds the 80-point threshold required for the top strength category. This indicates a robust password, supported by a combination of character types and sequences that maximize the bonus and minimize penalties .

Prime primordial numbers hold cryptographic significance as numbers that can be expressed as P# + 1 or P# - 1, where P# is the product of all prime numbers up to P. Verification involves confirming the number's primality and its alignment with the primordial condition. For example, 211 and 30029 are verified as prime primordial numbers because they fulfill these criteria .

The Robinson sequence is developed by analyzing the frequency of each digit appearing in a term, then constructing the next term by concatenating these frequencies followed by the digit itself in descending order. This process begins with U0, set to 0, and each subsequent term Un is derived from the digit counts of Un-1, repeated in increasing sequence complexity as n increases .

You might also like