How to mask a string in swift 4.2 - swift4.2

I wanna make a mask in a string.
let unmasked = "12345678900"
//string masked = "123.456.789-00"
This is the braziliam CPF format, i found nothing in Stack Overflow BR

I found a solution using a character array and array.insert to insert mask in defined index
Portuguese:
Eu encontrei uma solução usando um array de caracteres e a função array.insert que permite inserir qualquer string em um determinado index da matriz.
let cpf = "12345678900"
var characters = Array(cpf) //making a character array (criando um array de caracteres)
characters.insert(".", at: 3) //inserting "." in index 3 (inserindo "." no index 3)
//character = ["1","2","3",".","4","5","6","7","8","9","0","0"]
characters.insert(".", at: 7) // inserting "." in index 7 (inserindo "." no index 7)
//character = ["1","2","3",".","4","5","6",".","7","8","9","0","0"]
characters.insert("-", at: 11)// inserting "." in index 11 (inserindo "." no index 11)
//character = ["1","2","3",".","4","5","6",".","7","8","9","-","0","0"]
let masked = String(characters) //convert character to string
pint("cpf masked: ",masked)
//the masked will show: 123.456.789-00 (a mascara irá mostrar: 123.456.789-00)

Related

TypeError: Strings must be encoded before hashing

On this code:
##script qui brute force les hashs
import hashlib
while True :
try :
wordlist_user = input("entrez votre wordlist: ")
wordlist = open(wordlist_user, "r", encoding='utf-8')
hash = input('entrez le hash que vous oulez cracker (sha224) : ')
break
except :
print('Error')
for word in wordlist.readlines():
word = word.strip()
wordlist_hash = hashlib.sha224(word).hexdigest()
if (hash == wordlist_hash):
print('password trouve: ' +word)
else :
print('password non trouve')
I have this error
wordlist_hash = hashlib.sha224(word).hexdigest()
TypeError: Strings must be encoded before hashing
can someone help me ?
hashlib.sha224() takes bytes but word is a string. You'll want to convert the string to the utf-8 encoded bytes with word.encode(encoding = 'UTF-8', errors = 'strict')

Steganography program - converting python 2 to 3, syntax error in: base64.b64decode("".join(chars))

I have problem with the syntax in the last part of steg program. I tried to convert python 2 version (of the working code) to python 3, and this is the last part of it:
flag = base64.b64decode("".join(chars)) <- error
print(flag)
The program 1. encrypts the message in the Last Significiant Bits of the image as saves it as a new image. Then 2.decrypts the message, which is stored in "flag", and prints it.
* can the error be caused by the wrong type of input?:
message = input("Your message: ")
BELOW: UNHIDING PROGRAM
#coding: utf-8
import base64
from PIL import Image
image = Image.open("after.png")
extracted = ''
pixels = image.load()
#Iterating in 1st row
for x in range(0,image.width):
r,g,b = pixels[x,0]
# Storing LSB of each color
extracted += bin(r)[-1]
extracted += bin(g)[-1]
extracted += bin(b)[-1]
chars = []
for i in range(len(extracted)/8):
byte = extracted[i*8:(i+1)*8]
chars.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
flag = base64.b64decode(''.join(chars))
print flag
BELOW: HIDING PROGRAM:
import bitarray
import base64
from PIL import Image
with Image.open('before.png') as im:
pixels=im.load()
message = input("Your message: ")
encoded_message = base64.b64encode(message.encode('utf-8'))
#Convert the message into an array of bits
ba = bitarray.bitarray()
ba.frombytes(encoded_message)
bit_array = [int(i) for i in ba]
#Duplicate the original picture
im = Image.open("before.png")
im.save("after.png")
im = Image.open("after.png")
width, height = im.size
pixels = im.load()
#Hide message in the first row
i = 0
for x in range(0,width):
r,g,b = pixels[x,0]
#print("[+] Pixel : [%d,%d]"%(x,0))
#print("[+] \tBefore : (%d,%d,%d)"%(r,g,b))
#Default values in case no bit has to be modified
new_bit_red_pixel = 255
new_bit_green_pixel = 255
new_bit_blue_pixel = 255
if i<len(bit_array):
#Red pixel
r_bit = bin(r)
r_last_bit = int(r_bit[-1])
r_new_last_bit = r_last_bit & bit_array[i]
new_bit_red_pixel = int(r_bit[:-1]+str(r_new_last_bit),2)
i += 1
if i<len(bit_array):
#Green pixel
g_bit = bin(g)
g_last_bit = int(g_bit[-1])
g_new_last_bit = g_last_bit & bit_array[i]
new_bit_green_pixel = int(g_bit[:-1]+str(g_new_last_bit),2)
i += 1
if i<len(bit_array):
#Blue pixel
b_bit = bin(b)
b_last_bit = int(b_bit[-1])
b_new_last_bit = b_last_bit & bit_array[i]
new_bit_blue_pixel = int(b_bit[:-1]+str(b_new_last_bit),2)
i += 1
pixels[x,0] = (new_bit_red_pixel,new_bit_green_pixel,new_bit_blue_pixel)
#print("[+] \tAfter: (%d,%d,%d)"%(new_bit_red_pixel,new_bit_green_pixel,new_bit_blue_pixel))
im.save('after.png')
error
ValueError: string argument should contain only ASCII characters
help for base64.b64decode says:
b64decode(s, altchars=None, validate=False)
Decode the Base64 encoded bytes-like object or ASCII string s.
...
Considering that in Python 2 there were "normal" strs and unicode-strs (u-prefixed), I suggest taking closer look at what produce "".join(chars). Does it contain solely ASCII characters?
I suggest adding:
print("Codes:",[ord(c) for c in chars])
directly before:
flag = base64.b64decode("".join(chars))
If there will be number >127 inside codes, that mean it might not work as it is fit only for pure ASCII strs.

Encrypt data with DES ECB in Ruby

I am implementing an encryption in a project that I has in another java project.
The code in java project is this:
public static String cifraDES(String chave, String dado) throws Exception {
DESKeySpec keySpec = new DESKeySpec(hexStringToByteArray(chave));
SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
SecretKey passwordKey = kf.generateSecret(keySpec);
Cipher c = Cipher.getInstance("DES");
c = Cipher.getInstance("DES/ECB/NoPadding");
c.init(Cipher.ENCRYPT_MODE, passwordKey);
return bytesToHex(c.doFinal(hexStringToByteArray(dado)));
}
In Ruby project i want implement this encrypt too. But this dont work:
dado = "53495A45303030386E6F7661313031305858585858585858"
chave = "3455189635541968"
des = OpenSSL::Cipher.new('des-ecb').encrypt
des.key = chave
s = des.update(dado) + des.final
Base64.encode64(s).gsub(/\n/, "")
In terminal I recive this message:
'key' be must 8 bytes
And i need this return: b42e3dbfffd4bb5487a27fd702f079e287e6325767bfdd20
View:
http://des.online-domain-tools.com/link/1145159gOjlrPNRkaT/
You haven’t converted the key and data from hex strings, you can do that using pack:
dado = ["53495A45303030386E6F7661313031305858585858585858"].pack('H*')
(When you do this to the key, it is converted from 16 hexidecimal characters to 8 bytes, so not doing this step is causing the error are getting).
You haven’t specified no padding:
des.padding = 0
And you want the result hex encoded, not base 64. You can use unpack:
puts s.unpack('H*')[0]
Putting it all together:
dado = ["53495A45303030386E6F7661313031305858585858585858"].pack('H*')
chave = ["3455189635541968"].pack('H*')
des = OpenSSL::Cipher.new('des-ecb').encrypt
des.key = chave
des.padding = 0
s = des.update(dado) + des.final
puts s.unpack('H*')[0]
Result is b42e3dbfffd4bb5487a27fd702f079e287e6325767bfdd20.
The error seems pretty clear to me. The key you're using chave is 16 bytes. Your key has to be 8 bytes. So reduce the length of the key to 8 chars then try.

Why is my dataveiw filter crashing

i have a dataview from a data table i am trying to filter to see if there are duplicate values for a manufacture, Type and Serial number but i am getting an error
string strFilter = "Manufacture = " + strMake + " and Type = " + strModel + " and Serial Number = " + strSn;
strfilter = "Manufacture = ford 150 and Type = Raptor and Serial Number = 9999"
dv.RowFilter = strFilter;
this it the error i am getting
An unhandled exception of type 'System.Data.SyntaxErrorException' occurred in System.Data.dll
Additional information: Syntax error: Missing operand after 'Number' operator
You need single quotes for strings.Write serial number in brackets like [Serial number] if that is the name of your column.
For one you are missing a semi colon here.
strfilter = "Manufacture = ford 150 and Type = Raptor and Serial Number = 9999" <---------
:)

Error using tensorflow Graph Def can not be larger than 2GB

I'm using inception v3 model imageNet shape with tensorflow for image classification. The program is designed to classify a single image so I tried to modify it to classify a test image database. It classifies the images well but arrives at about 20 images it returns me the following error:File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1912, in as_graph_def
raise ValueError("GraphDef cannot be larger than 2GB.")
ValueError: GraphDef cannot be larger than 2GB.
Below the image label code that I modified:
# -*- coding: utf-8 -*-
import os, sys
import time
import tensorflow as tf
def chargement_image(path):
image = []
image = os.listdir(path)
return image
resultat = []
best = []
nbr = 0
som = 0
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
start_time = time.time()
# Chargement de la base de test
test_path = sys.argv[1]
list_img = chargement_image(test_path)
for i in range(len(list_img)):
image_path = test_path+list_img[i]
# Read in the image_data
image_data = tf.gfile.FastGFile(image_path, 'rb').read()
# Loads label file, strips off carriage return
label_lines = [line.rstrip() for line
in tf.gfile.GFile("retrained_labels.txt")]
# Unpersists graph from file
with tf.gfile.FastGFile("retrained_graph.pb", 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
with tf.Session() as sess:
# Feed the image_data as input to the graph and get first prediction
softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
predictions = sess.run(softmax_tensor, \
{'DecodeJpeg/contents:0': image_data})
#print(len(predictions))
# Trier pour afficher les étiquettes de la première prédiction par ordre de bon taux de classement
top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]
#print(top_k)
for node_id in top_k:
human_string = label_lines[node_id]
score = predictions[0][node_id]
resultat.append(score)
print('%s (score = %.5f)' % (human_string, score))
#print(score)
nbr += 1
best.append(resultat[0])
del resultat[:]
#print(best)
print(nbr)
print("=========================================")
#print(best)
#print(nbr)
for i in range(len(best)):
som += best[i]
taux_precision = float(100. * som / nbr)
print 'Precision: ' + str(taux_precision) + '%'
print("--- %s seconds ---" % (time.time() - start_time))
Try to put below line outside the for loop:
# Loads label file, strips off carriage return
label_lines = [line.rstrip() for line
in tf.gfile.GFile("retrained_labels.txt")]
# Unpersists graph from file
with tf.gfile.FastGFile("retrained_graph.pb", 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')

Resources