NodeMCU support encrypt and decrypt functions which are in crypto packages.
http://nodemcu.readthedocs.io/en/dev/en/modules/crypto/
This is manual for Crypto package.
crypto.encrypt()
Encrypts Lua strings.
Syntax
crypto.encrypt(algo, key, plain [, iv])
Parameters
algo
the name of the encryption algorithm to use, one of"AES-ECB"
for 128-bit AES in ECB mode"AES-CBC"
for 128-bit AES in CBC mode
key
the encryption key as a string; for AES encryption this MUST be 16 bytes longplain
the string to encrypt; it will be automatically zero-padded to a 16-byte boundary if necessaryiv
the initilization vector, if using AES-CBC; defaults to all-zero if not given
Returns
The encrypted data as a binary string. For AES this is always a multiple of 16 bytes in length.
Crypto package AES-ECB using no padding. So you should make 16 multiple bytes array from plain text. And NodeMCU use EUCKR encoding in crypto package.NodeMCU
1 2 3 4 5 6 | key = "1234567890abcdef" cipher = crypto.encrypt("AES-ECB", key, "Hi, I'm secret!") print(crypto.toBase64(cipher)) cipher = crypto.encrypt("AES-ECB", key, "가나다라마바사") print(crypto.toBase64(cipher)) |
Result
LQ95s23+t6PK0mmokJFSYg==w9kOL6y40iVqhuGdWt6vLw==
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public static void main( String[] args) throws Exception { String keyValue = "1234567890abcdef"; String encryptedText1 = "LQ95s23+t6PK0mmokJFSYg=="; String encryptedText2 = "w9kOL6y40iVqhuGdWt6vLw=="; java.nio.charset.Charset charset = java.nio.charset.Charset.forName( "euckr"); java.security.Key key = new javax.crypto.spec.SecretKeySpec( keyValue.getBytes( charset), "AES"); javax.crypto.Cipher cipher = Cipher.getInstance( "AES/ECB/NoPadding"); cipher.init( Cipher.DECRYPT_MODE, key); System.out.println( "DecryptedText1=" + new String( cipher.doFinal( org.apache.commons.codec.binary.Base64.decodeBase64( encryptedText1.getBytes( charset))), charset)); System.out.println( "DecryptedText2=" + new String( cipher.doFinal( org.apache.commons.codec.binary.Base64.decodeBase64( encryptedText2.getBytes( charset))), charset)); } |
No comments:
Post a Comment