Encrypting and decrypting sample with ruby and openssl - encryption

i'm trying to do a sample app, for testing purposes vs other people development, and would like to print to the screen the encrypted string, and put it back to a decrypt mechanism....I just don't seem to be finding the way to do this...I've tried base64 and unpack, and feel this is the way, but am not getting there.
require 'openssl'
require 'base64'
def ask(prompt)
loop do
print prompt, ' '
$stdout.flush
s = gets
return s.chomp
end
end
def aes(m,k,t)
(aes = OpenSSL::Cipher::Cipher.new('aes-256-cbc').send(m)).key = Digest::SHA256.digest(k)
aes.update(t) << aes.final
end
def encrypt(key, text)
aes(:encrypt, key, text)
end
def decrypt(key, text)
aes(:decrypt, key, text)
end
def my_decrypt
#crypted = ask("Crypted data: ")
decrypted = decrypt("12345678911131511192123252729412",#crypted)
print decrypted
end
def my_encrypt
#decrypted = ask("Data to encrypt: ")
crypted = encrypt("12345678911131511192123252729412",#decrypted)
print crypted
end
option=ask("Option 1 - Encrypt, 2 decrypt")
case option
when "1" then my_encrypt
when "2" then my_decrypt
else print "Option not valid"
end
Anyone to the rescue?
Thank you

After some fight, i finally got it...I just need to convert the binary to Hex, and then back to binary...
Two notes : to convert a binary to hex, you can use String.unpack, which will return an array.
To convert an hex to binary, you first need to build it as an array ["anystringhere"] , and then pack it back to binary using Array.pack
Here is the resulting code
require 'openssl'
require 'base64'
def ask(prompt)
loop do
print prompt, ' '
$stdout.flush
s = gets
return s.chomp
end
end
def aes(m,k,t)
(aes = OpenSSL::Cipher::Cipher.new('aes-256-cbc').send(m)).key = Digest::SHA256.digest(k)
aes.update(t) << aes.final
end
def encrypt(key, text)
aes(:encrypt, key, text)
end
def decrypt(key, text)
aes(:decrypt, key, text)
end
def my_decrypt
#crypted = ask("Crypted data: ")
decrypted = decrypt("12345678911131517192123252729313",[#crypted].pack('H*'))
print decrypted
end
def my_encrypt
#decrypted = ask("Data to encrypt: ")
crypted = encrypt("12345678911131517192123252729313",#decrypted)
print u=crypted.unpack('H*')
end
option=ask("Option 1 - Encrypt, 2 decrypt")
case option
when "1" then my_encrypt
when "2" then my_decrypt
else print "Option not valid"
end

Related

How to encrypt RSA in lua?

I want to convert rsa in Lua using the following parameters. I need to send a 6-digit code as RSA encrypted to perform a payment transaction. I couldn't do this in Lua. Can you share a code sample?
Exponent=AQAB
Modulus=1EYDa43a8My50miTEK2miAzw8Rl/1HqG+XT0LuBdoKtZLdKe35xAOlr0DTk/Bp6...
I don't want to share the full public key for security reasons.
The code sample I developed is as follows.
prm_inData = "123456";
function Encryption(prm_inData)
local outData1 = ""
if(prm_inData ~= nil) then
local IVVee = ""
local len = ""
local len2 = ""
IVVee = AQAB;
len = string.len(prm_inData)
rsa = vpos.crypt.RSA()
if(rsa ~= nil) then
enc= rsa:getPublicKey("1EYDa43a8My50miTEK2miAzw...");
outData1 = rsa:encrypt(prm_inData, IVVee)
end
len2 = string.len(outData1)
return outData1
end
end
The code sample I developed is as follows. When I encrypt it returns 1281. I think I did the operation wrong. Where am I doing wrong? I would appreciate your help.

How To Encrypt File In QB64

Am attempting to encrypt a file using this program in QB64.
It does not actually encrypt the file and always returns successful. Why?
DECLARE LIBRARY
FUNCTION EncryptFile (f$)
FUNCTION DecryptFile (f$, BYVAL f&)
END DECLARE
PRINT "Enter filename";
INPUT f$
IF f$ <> "" THEN
f$ = f$ + CHR$(0)
x = EncryptFile(f$)
IF x = 0 THEN
PRINT "Error encrypting file."
ELSE
PRINT "File encrypted."
END IF
END IF
END
The solution was to detect the encryption status of a filename such as this:
REM checks encryption status of a filename
DECLARE DYNAMIC LIBRARY "advapi32"
FUNCTION FileEncryptionStatusA% (f$, f&)
END DECLARE
DO
PRINT "Filename";
INPUT f$
IF f$ = "" THEN END
x = FileEncryptionStatusA(f$, f&)
IF x = 0 THEN
PRINT "Error accessing file."
END IF
IF x THEN
SELECT CASE f&
CASE 0
PRINT "File can be encrypted."
CASE 1
PRINT "File is encrypted."
CASE 2
PRINT "File is system."
CASE 3
PRINT "File is root."
CASE 4
PRINT "File is system directory."
CASE 5
PRINT "Encryption status unknown."
CASE 6
PRINT "File system does not support encryption."
CASE 7 ' reserved
CASE 8
PRINT "File is read-only."
END SELECT
END IF
LOOP
END

Removing newline character

So currently I've had a problem for the past few hours. I've looked through many stack overflow posts and have tried every suggestion. What my problem is, is I have a program that grabs words from a text file and gives them an MD5 encryption.
fileName = raw_input("> ")
if fileName.endswith(".txt") or fileName.endswith(".lst"):
fopen = open(fileName, 'r')
else:
fileName = fileName + ".txt"
fopen = open(fileName, 'r')
m = hashlib.md5()
for line in fopen:
sleep(1)
m.update(line)
encHash = m.hexdigest()
hashed = [line, encHash]
new_line = []
for elem in hashed:
new_line.extend(elem.strip('\n').split(' '))
searchfile = open("Passwords.txt").read()
if line in searchfile:
print ""
else:
fopen = open("Passwords.txt", 'a')
fopen.write(str(hashed))
fopen.write("\n")
fopen.close
print str(new_line)
Now as you can see, I've already dealt with the new line characters being outputted. But the encrypted version still has the \n at the end. So instead of "12345" being encrypted "12345\n" is.
I've tried rstrip(), and strip(). But it doesn't seem to work! Any help would be greatly appreciated.
Thanks
Paul
EDIT
I don't know what I did, I just re-wrote the code and its working fine! Thanks for all the suggestions.
elif choice == "2":
os.system('clear')
fileName = raw_input('Filename: ')
fopen = open(fileName, 'rb')
for line in fopen:
line = line.rstrip('\n')
enc = hashlib.md5()
enc.update(line)
encHash = enc.hexdigest()
hashed = {line:encHash}
fwrite = open('Password.txt', 'a')
hashed = str(hashed)
data = open("Password.txt").read()
if hashed in data:
print hashed
else:
fwrite.write(hashed)
fwrite.write("\n")
fwrite.close
print hashed
I don't know Python but it sounds like it could be related to the way you're opening the file.
Try using open(fileName, 'rb') instead of open(fileName, 'r').
This link describes the \r\n \n diffs. Opening a file up as binary will convert the newline character to newline sequence respective of the system you are running the code on.
http://docs.python.org/2/library/functions.html#open

Digits Regular Expression Validator

i need a regular expression validation for
numeric digits grouped as X-XXXXX-XXX-X
can any one help?
Regex reg = new Regex("\b[0-9]\-[0-9]{5}\-[0-9]{3}\-[0-9]\b");
Here is what I use for checking social security numbers that user's input:
Public Shared Function CheckSSNFormat(ByVal text As String) As Boolean
Dim digits As String = Regex.Replace(text, "[^0-9]", "")
Return digits.Length = 9
End Function
It doesn't check that they are input in a specific format, but that might be better depending on what you really need -- so just thought I'd give you another option, just incase.
The above just removes everything except digits, and returns true if there are 9 digits (a valid SS#). It does mean some goofy user could enter something like: hello123456789 and it would accept it as valid, but that is fine for me, and I'd rather do that than not accept 123456789 just because I was looking for 123-45-6789 only.
Later I use this to save to my database:
Public Shared Function FormatSSNForSaving(ByVal text As String) As String
If text = "" Then text = "000-00-0000"
Return Regex.Replace(text, "[^0-9]", "")
End Function
and this anytime I want to display the value (actually I use this one for phone numbers, turns out I never display the SS# so don't have a function for it):
Public Shared Function FormatPhoneForDisplay(ByVal text As String) As String
If text.Length <> 10 Then Return text
Return "(" & text.Substring(0, 3) & ") " & text.Substring(3, 3) & "-" & text.Substring(6, 4)
End Function
(^\d{1}-\d{5}-\d{3}-\d{1}$), this should do.
[0-9]-[0-9]{5}-[0-9]{3}-[0-9]
you could also use round brackets to extract the numbers if you want:
([0-9])-([0-9]{5})-([0-9]{3})-([0-9])
and get the values with $1 $2 etc. in the Regex.Replace() function
Regex pattern = new Regex("\b\d-\d{5}-\d{3}-\d\b");
\b - word boundary
\d - digit

Simple encrypt/decrypt functions in Classic ASP

Are there any simple encrypt/decrypt functions in Classic ASP?
The data that needs to be encrypted and decrypted is not super sensitive. So simple functions would do.
4guysfromrolla.com: RC4 Encryption Using ASP & VBScript
See the attachments at the end of the page.
The page layout looks a bit broken to me, but all the info is there. I made it readable it by deleting the code block from the DOM via bowser development tools.
Try this:
' Encrypt and decrypt functions for classic ASP (by TFI)
'********* set a random string with random length ***********
cryptkey = "GNQ?4i0-*\CldnU+[vrF1j1PcWeJfVv4QGBurFK6}*l[H1S:oY\v#U?i,oD]f/n8oFk6NesH--^PJeCLdp+(t8SVe:ewY(wR9p-CzG<,Q/(U*.pXDiz/KvnXP`BXnkgfeycb)1A4XKAa-2G}74Z8CqZ*A0P8E[S`6RfLwW+Pc}13U}_y0bfscJ<vkA[JC;0mEEuY4Q,([U*XRR}lYTE7A(O8KiF8>W/m1D*YoAlkBK#`3A)trZsO5xv#5#MRRFkt\"
'**************************** ENCRYPT FUNCTION ******************************
'*** Note: bytes 255 and 0 are converted into the same character, in order to
'*** avoid a char 0 which would terminate the string
function encrypt(inputstr)
Dim i,x
outputstr=""
cc=0
for i=1 to len(inputstr)
x=asc(mid(inputstr,i,1))
x=x-48
if x<0 then x=x+255
x=x+asc(mid(cryptkey,cc+1,1))
if x>255 then x=x-255
outputstr=outputstr&chr(x)
cc=(cc+1) mod len(cryptkey)
next
encrypt=server.urlencode(replace(outputstr,"%","%25"))
end function
'**************************** DECRYPT FUNCTION ******************************
function decrypt(byval inputstr)
Dim i,x
inputstr=urldecode(inputstr)
outputstr=""
cc=0
for i=1 to len(inputstr)
x=asc(mid(inputstr,i,1))
x=x-asc(mid(cryptkey,cc+1,1))
if x<0 then x=x+255
x=x+48
if x>255 then x=x-255
outputstr=outputstr&chr(x)
cc=(cc+1) mod len(cryptkey)
next
decrypt=outputstr
end function
'****************************************************************************
Function URLDecode(sConvert)
Dim aSplit
Dim sOutput
Dim I
If IsNull(sConvert) Then
URLDecode = ""
Exit Function
End If
'sOutput = REPLACE(sConvert, "+", " ") ' convert all pluses to spaces
sOutput=sConvert
aSplit = Split(sOutput, "%") ' next convert %hexdigits to the character
If IsArray(aSplit) Then
sOutput = aSplit(0)
For I = 0 to UBound(aSplit) - 1
sOutput = sOutput & Chr("&H" & Left(aSplit(i + 1), 2)) & Right(aSplit(i + 1), Len(aSplit(i + 1)) - 2)
Next
End If
URLDecode = sOutput
End Function
I know is a bit late for BrokenLink, but for the record and others like me who were looking for the same.
I found this https://www.example-code.com/vbscript/crypt_aes_encrypt_file.asp.
It needs to install a chilkat ActiveX component on WindowsServer. But this inconvenient becomes convenient when looking resources and processing time.
Its very easy to use, and the given example is pretty clear. To make it your own, just change the "keyHex" variable value and voilá.

Resources