Welcome Guest, you are in: Login

Fruit Of The Shed

Navigation (MMBasic)






Search the wiki

»


Page History: Simple Encryption

Compare Page Revisions



« Older Revision - Back to Page History - Newer Revision »


Page Revision: 2019/06/05 12:37


All communications in public space should really be encrypted.

Various forms of encryption exist and at their simplest they used a "shared secret" - a key string that is used to encrypt and decrypt a message using mathematical progression. Such encryption is termed "symmetrical" as the same key is used to both encrypt and decrypt. It is crucial that the key remain secret for obvious reasons.

Stronger, asymmetrical, encryption uses two separate keys - a public key used to encrypt the data and a private key for decrypting. The public key cannot be used to decrypt the message and so it does not matter that it becomes openly known or shared. The private key must remain secret in the same sense as that for symmetrical encryption.

The RC4 Encryption and Decryption Functions found elsewhere in this library provide a common form of symmetrical encryption and although RC4 is deprecated it still provides a good level of secrecy with a sufficiently complex key of at least 32 characters (256 bits).

An encryption suite such as RC4 is mathematically intensive and smaller micro-controllers, especially running at lower clock speeds, can struggle to maintain timings in tight spaces purely because it can take a good deal of time to generate the encrypted string or regenerate the original.

If only simple obfuscation is required, RC4 can be overkill and the timings prohibitive. The below functions use a simple rotating XOR of a shared secret key. The main advantage is the routines are very quick and produce a good basic level of encryption - not to the level of RC4, MD5 or BlowFish etc. but certainly enough to prevent clear-text snooping on traffic.

Examples
z$=Encrypt$("mary had a little lamb")
z$=Decrypt$(mysecretmessage$)

Preamble
	CONST KEY$=">4!1x4q3z4+7%4{9?5\3HhH^5$9=6@1~6,7_7|1)7'3]7[9:8<3*8S9I9l7Z1eT0r1"

The Code
	FUNCTION ENCRYPT$(A$)
		LOCAL N,P AS INTEGER
		LOCAL B$
		P=1
		FOR N=1 TO LEN(A$)
			B$=B$+HEX$(ASC(MID$(A$,N,1),2) XOR ASC(MID$(KEY$,P,1)),2)
			P=P+1:IF P>LEN(KEY$) THEN P=1
		NEXT
		ENCRYPT$=B$
	END FUNCTION

	FUNCTION DECRYPT$(A$)
		LOCAL N,P AS INTEGER
		LOCAL B$
		P=1
		FOR N=1 TO LEN(A$) STEP 2
			B$=B$+chr$(val("&H"+MID$(A$,N,2)) xor asc(MID$(KEY$,P,1)))
			P=P+1:IF P>LEN(KEY$) THEN P=1
		NEXT
		DECRYPT$=B$
	END FUNCTION