I am trying to create a custom encryption/decryption code in python. I read few articles and found that I can store the encryption ciphers in the dictionary. I tried using it but it is not working. keys will be letters in alphabetical order(A-Z) and values will be the letters that I want to put(ciphers). There is no specifics shift pattern in the encryption cipher. There are also numbers(0-9) in the encryption-decryption. they are in sequence though.
dict = {'A' : 'O', 'B' : 'P', 'C' : 'J' ......'Z' : 'Z', ....
'0' : 9, '1' : 8, ............'8' : 1, '9' : 0}
These encrypted password will be stored in a database. I need help to create the code to encrypt and decrypt the password. If there's any other method to start with please let me know.
If you don't want to use the Python Cryptography Module...
Here's some code that may help:
I'm replacing your dict with the name en_dict
#unencrypted_item should be a string
def encrypt(unencrypted_item):
result = ""
for i in unencrypted_item:
result+=en_dict[i]
return result
def encrypt(encrypted_item):
result = ""
for i in encrypted_item:
for n in en_dict:
if en_dict[n] == i:
result += n
break
return result
Try mapping the original string with the keys in your dictionary.
mapping = {'A':'Z', 'B':'C', '1':'0', '2':'7'}
reverse_mapping = dict((j,i) for i,j in mapping.items())
string_to_encrypt = 'AB1'
encrypted_string = ''.join(map(mapping.__getitem__, string_to_encrypt))
print(encrypted_string) #ZC0
decrypted_string = ''.join(map(reverse_mapping.__getitem__, encrypted_string))
print(decrypted_string) #AB1
Firstly, I hope that you plan to use your encryption scheme for academic purposes only because this simple substitution cipher is very insecure. For the most basic level of security you should look at storing salted hashes of user passwords instead, or use something like bcrypt.
WRT to your specific question, use your mapping dictionary with str.translate() to translate the string in one go without the need to explicitly loop in your code, or use other functions such as map() and join().
encrypt_dict = {'A': 'O', 'B': 'P', 'C': 'J', 'Z': 'Z', '0': 9, '1': 8, '8': 1, '9': 0}
tr_encrypt = {ord(str(k)): ord(str(encrypt_dict[k])) for k in encrypt_dict}
tr_decrypt = {tr_encrypt[k]: k for k in tr_encrypt}
plaintext = 'ABCZ0189'
ciphertext = plaintext.translate(tr_encrypt)
>>> ciphertext
'OPJZ9810'
assert ciphertext.translate(tr_decrypt) == plaintext
plaintext = 'THIS IS test 128'
ciphertext = plaintext.translate(tr_encrypt)
>>> ciphertext
'THIS IS test 821'
assert ciphertext.translate(tr_decrypt) == plaintext
The first few lines set up encryption and decryption translation tables in the form required by str.translate(). Then it's simply a matter of calling translate on the string to encrypt and decrypt as required.
The second example shows that any character in the string that is not present in the translation table is left unchanged which may or may not be what you want. You can create a translation mapping that covers all expected characters, but that's potentially a lot if you are using unicode.
I think this is what you want. You can use string.printable[:61] where string.printable prints all the ASCII characters and [:61] takes all characters from index 0 to 61 - which are letters and numbers
import string
import random
normla_l=list(string.printable[:61])
new_l=list(string.printable[:61])
random.shuffle(new_l)
see_list={x:y for x,y in zip(normla_l,new_l)}
def change_list(char):
return see_list.get(char) if char!='' else random.choice(normla_l)
x=input("Enter string: ")
print(''.join([change_list(char.strip()) for char in x]).strip())
Sample
Enter string: This string will be encrypted
Xqv7G74HvTxbPv55psIVITzHhg4IN
Related
So I would like to make a function in Rust where I can input a string and get the ciphertext out of it. I'm using the Kyber1024 KEM and I can't find a way to input a custom string to turn into a cipher.
Documentation: https://docs.rs/pqcrypto-kyber/0.7.6/pqcrypto_kyber/kyber1024/index.html
Crate: https://crates.io/crates/pqcrypto-kyber
The usage in the documentation just says this:
use pqcrypto_kyber::kyber1024::*;
let (pk, sk) = keypair();
let (ss1, ct) = encapsulate(&pk);
let ss2 = decapsulate(&ct, &sk);
assert!(ss1 == ss2);
Nowhere does it illustrate (as far as I can see) a way for a user to insert a custom string for example so it can get converted into ciphertext.
How do I do this?
Swiftui dictionaries have the feature that the value returned by using key access is always of type "optional". For example, a dictionary that has type String keys and type String values is tricky to access because each returned value is of type optional.
An obvious need is to assign x=myDictionary[key] where you are trying to get the String of the dictionary "value" into the String variable x.
Well this is tricky because the String value is always returned as an Optional String, usually identified as type String?.
So how is it possible to convert the String?-type value returned by the dictionary access into a plain String-type that can be assigned to a plain String-type variable?
I guess the problem is that there is no way to know for sure that there exists a dictionary value for the key. The key used to access the dictionary could be anything so somehow you have to deal with that.
As described in #jnpdx answer to this SO question (How do you assign a String?-type object to a String-type variable?), there are at least three ways to convert a String? to a String:
import SwiftUI
var x: Double? = 6.0
var a = 2.0
if x != nil {
a = x!
}
if let b = x {
a = x!
}
a = x ?? 0.0
Two key concepts:
Check the optional to see if it is nil
if the optional is not equal to nil, then go ahead
In the first method above, "if x != nil" explicitly checks to make sure x is not nil be fore the closure is executed.
In the second method above, "if let a = b" will execute the closure as long as b is not equal to nil.
In the third method above, the "nil-coalescing" operator ?? is employed. If x=nil, then the default value after ?? is assigned to a.
The above code will run in a playground.
Besides the three methods above, there is at least one other method using "guard let" but I am uncertain of the syntax.
I believe that the three above methods also apply to variables other than String? and String.
I wrote this function to generate random unique id's for my test cases:
func uuid(t *testing.T) string {
uidCounterLock.Lock()
defer uidCounterLock.Unlock()
uidCounter++
//return "[" + t.Name() + "|" + strconv.FormatInt(uidCounter, 10) + "]"
return "[" + t.Name() + "|" + string(uidCounter) + "]"
}
var uidCounter int64 = 1
var uidCounterLock sync.Mutex
In order to test it, I generate a bunch of values from it in different goroutines, send them to the main thread, which puts the result in a map[string]int by doing map[v] = map[v] + 1. There is no concurrent access to this map, it's private to the main thread.
var seen = make(map[string]int)
for v := range ch {
seen[v] = seen[v] + 1
if count := seen[v]; count > 1 {
fmt.Printf("Generated the same uuid %d times: %#v\n", count, v)
}
}
When I just cast the uidCounter to a string, I get a ton of collisions on a single key. When I use strconv.FormatInt, I get no collisions at all.
When I say a ton, I mean I just got 1115919 collisions for the value [TestUuidIsUnique|�] out of 2227980 generated values, i.e. 50% of the values collide on the same key. The values are not equal. I do always get the same number of collisions for the same source code, so at least it's somewhat deterministic, i.e. probably not related to race conditions.
I'm not surprised integer overflow in a rune would be an issue, but I'm nowhere near 2^31, and that wouldn't explain why the map thinks 50% of the values have the same key. Also, I wouldn't expect a hash collision to impact correctness, just performance, since I can iterate over the keys in a map, so the values are stored there somewhere.
In the output, all runes printed are 0xEFBFBD. It's the same number of bits as the highest valid unicode code point, but that doesn't really match either.
Generated the same uuid 2 times: "[TestUuidIsUnique|�]"
Generated the same uuid 3 times: "[TestUuidIsUnique|�]"
Generated the same uuid 4 times: "[TestUuidIsUnique|�]"
Generated the same uuid 5 times: "[TestUuidIsUnique|�]"
...
Generated the same uuid 2047 times: "[TestUuidIsUnique|�]"
Generated the same uuid 2048 times: "[TestUuidIsUnique|�]"
Generated the same uuid 2049 times: "[TestUuidIsUnique|�]"
...
What's going on here? Did the go authors assume that hash(a) == hash(b) implies a == b for strings? Or am I just missing something silly? go test -race isn't complaining either.
I'm on macOS 10.13.2, and go version go1.9.2 darwin/amd64.
String conversion of an invalid rune returns a string containing the unicode replacement character: "�".
Use the strconv package to convert an integer to text.
I am using openresty/1.7.7.2 with Lua 5.1.4. I am receiving int64 in request and i have it's string format saved in DB (can't change DB schema or request format). I am not able to match both of them.
local i = 913034578410143848 --request
local p = "913034578410143848" -- stored in DB
print(p==tostring(i)) -- return false
print(i%10) -- return 0 ..this also doesn't work
Is there a way to convert int64 to string and vice versa if possible?
update:
I am getting i from protobuf object. proto file describe i as int64. I am using pb4lua library for protobuf.
ngx.req.read_body()
local body = ngx.req.get_body_data()
local request, err = Request:load(body)
local i = request.id
Lua 5.1 can not represent integer values larger than 2^53.
Number literal not excaption. So you can not just write
local i = 913034578410143848.
But LuaJIT can represent int64 values like boxed values.
Also there exists Lua libraries to make deal with large numbers.
E.g. bn library.
I do not know how your pb4lua handle this problem.
E.g. lua-pb library uses LuaJIT boxed values.
Also it provide way to specify user defined callback to make int64 value.
First I suggest figure out what real type of your i value (use type function).
All other really depends on it.
If its number then I think pb4lua just loose some info.
May be it just returns string type so you can just compare it as string.
If it provide LuaJIT cdata then this is basic function to convert string
to int64 value.
local function to_jit_uint64(str)
local v = tonumber(string.sub(str, 1, 9))
v = ffi.new('uint64_t', v)
if #str > 9 then
str = string.sub(str, 10)
v = v * (10 ^ #str) + tonumber(str)
end
return v
end
What's the algorithm for creating hash (sha-1 or MD5) of an RSA public key? Is there a standard way to do this? Hash just the modulus, string addition of both and then take a hash? Is SHA-1 or MD5 usually used?
I want to use it to ensure that I got the right key (have the sender send a hash, and I calculate it myself), and log said hash so I always know which exact key I used when I encrypt the payload.
Based on the OpenSSH source code, the way that a fingerprint is generated for RSA keys is to convert n and e from the public key to big-endian binary data, concatenate the data and then hash that data with the given hash function.
Portions of the OpenSSH source code follows. The comments were added to clarify what is happening.
// from key_fingerprint_raw() in key.c
switch (k->type) {
case KEY_RSA1:
// figure out how long n and e will be in binary form
nlen = BN_num_bytes(k->rsa->n);
elen = BN_num_bytes(k->rsa->e);
len = nlen + elen;
// allocate space for n and e and copy the binary data into blob
blob = xmalloc(len);
BN_bn2bin(k->rsa->n, blob);
BN_bn2bin(k->rsa->e, blob + nlen);
...
// pick a digest to use
switch (dgst_type) {
case SSH_FP_MD5:
md = EVP_md5();
break;
case SSH_FP_SHA1:
md = EVP_sha1();
break;
...
// hash the data in blob (n and e)
EVP_DigestInit(&ctx, md);
EVP_DigestUpdate(&ctx, blob, len);
EVP_DigestFinal(&ctx, retval, dgst_raw_length);
From the BN_bn2bin manual page:
BN_bn2bin(a, to) converts the absolute value of a into big-endian form and stores it at to. to must point to BN_num_bytes(a) bytes of memory.