AES Encryption using Scripting

Hi,

I need to encrypt a string using AES 128. Is there a way to do it within Ignition? I tried with PyCrypto library, it didn’t work.

Thanks,

From what I see, PyCrypto uses C libraries and you need something compatible with Jython.

You could translate the Java code here into Jython fairly easily; drop type information, curly braces, and add qualified imports (from package import Class) at the top of the file:

1 Like

I had a similar Idea.

Found this:
Java program to Encrypt/Decrypt String Using AES 128

And converted it to this:

from java.util import Base64
from javax.crypto import Cipher
from javax.crypto.spec import IvParameterSpec
from javax.crypto.spec import SecretKeySpec

import java.lang.Exception
logger = system.util.getLogger('encryptionLogger')

_encryptionKey = 'ABCDEFGHIJKLMNOP'
_characterEncoding = 'UTF-8'
_cipherTransformation = 'AES/CBC/PKCS5PADDING'
_aesEncryptionAlgorithem = 'AES'

def encrypt(plainText):
	encryptedText = ''
	try:
		cipher = Cipher.getInstance(_cipherTransformation)
		key = _encryptionKey.encode('utf-8')
		secretKey = SecretKeySpec(key,'AES')
		ivParameterSpec = IvParameterSpec(key)
		cipher.init(Cipher.ENCRYPT_MODE,secretKey,ivParameterSpec)
		cipherText = cipher.doFinal(plainText.encode('UTF-8'))
		encoder = Base64.getEncoder()
		encryptedText = encoder.encodeToString(cipherText)
	except Exception, e:
		logger.warnf('Encrypt Exception: %s',e)
	
	return encryptedText
	

def decrypt(encryptedText):
	decryptedText = ''
	
	try:
		cipher = Cipher.getInstance(_cipherTransformation)
		key = _encryptionKey.encode('utf-8')
		secretKey = SecretKeySpec(key,'AES')
		ivParameterSpec = IvParameterSpec(key)
		cipher.init(Cipher.DECRYPT_MODE,secretKey,ivParameterSpec)
		decoder = Base64.getDecoder()
		cipherText = decoder.decode(encryptedText.encode('UTF-8'))
		decryptedText = ''.join(map(chr,cipher.doFinal(cipherText)))
	except Exception, e:
		logger.warnf('Decrypt Exception: %s',e)
	
	return decryptedText

ran the following as a test:

encryptedString = encrypt('test string')
print encryptedString
print decrypt(encryptedString)

Output was:

>>> 
HZX0KjZSzXpdUOinZmq45g==
test string
>>> 
12 Likes