fork download
  1. class CryptUtils
  2. {
  3. private static String TRANSFORMATION = "AES/CBC/PKCS5Padding";
  4. private static String ALGORITHM = "AES";
  5. private static String DIGEST = "SHA-256";
  6. private static Cipher _cipher;
  7. private static SecretKey _password;
  8. private static IvParameterSpec _IVParamSpec;
  9. //16-byte private key
  10. private static byte[] iv = "radomaesvectors".getBytes();
  11. public static String encryptDecrypt(String Mode, String cryptText, String passKey) throws
  12.  
  13.  
  14. byte[] decryptedVal = null;
  15. String retText="";
  16. try {
  17. //Encode digest
  18. MessageDigest digest;
  19. digest = MessageDigest.getInstance(DIGEST);
  20. byte[] bytehash = digest.digest(passKey.getBytes(StandardCharsets.UTF_8));
  21.  
  22. String strHash="";
  23.  
  24. Formatter formatter = new Formatter();
  25. for (byte myByte: bytehash) {
  26. strHash="";
  27. strHash = String.format("%02x", myByte);
  28. formatter.format(StringUtils.leftPad(strHash, 2, "0"));
  29. }
  30.  
  31. strHash = formatter.toString();
  32.  
  33.  
  34. if (strHash.length() > 32) {
  35. strHash = strHash.substring(0, 32);
  36. }
  37.  
  38. byte[] bytekeytemp = strHash.getBytes(StandardCharsets.UTF_8);
  39.  
  40. byte[] bytekey = new byte[32];
  41.  
  42.  
  43. System.arraycopy(bytekeytemp, 0, bytekey, 0, 32);
  44.  
  45.  
  46. _password = new SecretKeySpec(bytekey, ALGORITHM);
  47.  
  48. //Initialize objects
  49.  
  50. _cipher = Cipher.getInstance(TRANSFORMATION);
  51.  
  52. _IVParamSpec = new IvParameterSpec(iv);
  53.  
  54.  
  55. if (Mode.equals("ENCRYPT")){
  56.  
  57. _cipher.init(Cipher.ENCRYPT_MODE, _password, _IVParamSpec);
  58.  
  59.  
  60.  
  61. byte[] ciphertext = _cipher.doFinal(cryptText.getBytes(StandardCharsets.UTF_8));
  62.  
  63. byte[] encodedValue = Base64.getEncoder().encode(ciphertext);
  64.  
  65.  
  66. String encryptedVal = new String(encodedValue);
  67.  
  68.  
  69. encryptedVal = encryptedVal.replace("+", "-");
  70. encryptedVal = encryptedVal.replace("/", "_");
  71.  
  72.  
  73. retText = encryptedVal;
  74. }
  75. else {
  76.  
  77. _cipher.init(Cipher.DECRYPT_MODE, _password, _IVParamSpec);
  78.  
  79. cryptText = cryptText.replace("-", "+");
  80. cryptText = cryptText.replace("_", "/");
  81.  
  82.  
  83.  
  84. byte[] decodedValue =
  85. Base64.getDecoder().decode(cryptText.getBytes(StandardCharsets.UTF_8));
  86.  
  87.  
  88. decryptedVal = _cipher.doFinal(decodedValue);
  89.  
  90. retText = new String(decryptedVal);
  91.  
  92. }
  93. throw new Exception("Encryption error, No such algorithm ->" + ALGORITHM);
  94. } catch (NoSuchPaddingException e) {
  95. throw new Exception("Encryption error, No such padding PKCS7");
  96. } catch (Exception e) {
  97. throw new Exception("Encryption error:" + exceptionToString(e));
  98. }
  99.  
  100. return retText;
  101. }
  102.  
  103.  
  104.  
  105.  
  106. import Crypto.Cipher.AES
  107. import Crypto.Random
  108. import base64
  109. import binascii
  110. import hashlib
  111.  
  112.  
  113. class Cipher_AES:
  114. pad_default = lambda x, y: x + (y - len(x) % y) * " ".encode("utf-8")
  115. unpad_default = lambda x: x.rstrip()
  116. pad_user_defined = lambda x, y, z: x + (y - len(x) % y) * z.encode("utf-8")
  117. unpad_user_defined = lambda x, z: x.rstrip(z)
  118. pad_pkcs5 = lambda x, y: x + (y - len(x) % y) * chr(y - len(x) % y).encode("utf-8")
  119. # pad_pkcs5=lambda x, y: "0".encode('utf-8') *(y - len(x) % y) + x
  120. unpad_pkcs5 = lambda x: x[:-ord(x[-1])]
  121. # unpad_pkcs5=lambda x: x[-ord(x[-1]):]
  122.  
  123. def __init__(self, key="abcdefgh12345678", iv=Crypto.Random.new().read(Crypto.Cipher.AES.block_size)):
  124. self.__key = key
  125. self.__iv = iv
  126.  
  127. def set_key(self, key):
  128. self.__key = key
  129.  
  130. def get_key(self):
  131. return self.__key
  132.  
  133. def set_iv(self, iv):
  134. self.__iv = iv
  135.  
  136. def get_iv(self):
  137. return self.__iv
  138.  
  139. def Cipher_MODE_ECB(self):
  140. self.__x = Crypto.Cipher.AES.new(self.__key.encode("utf-8"), Crypto.Cipher.AES.MODE_ECB)
  141.  
  142. def Cipher_MODE_CBC(self):
  143. self.__x = Crypto.Cipher.AES.new(self.__key.encode("utf-8"), Crypto.Cipher.AES.MODE_CBC,self.__iv.encode("utf-8"))
  144.  
  145. def encrypt(self, text, cipher_method, pad_method="", code_method=""):
  146. if cipher_method.upper() == "MODE_ECB":
  147. self.Cipher_MODE_ECB()
  148. elif cipher_method.upper() == "MODE_CBC":
  149. self.Cipher_MODE_CBC()
  150. cipher_text = b"".join([self.__x.encrypt(i) for i in self.text_verify(text.encode("utf-8"), pad_method)])
  151. if code_method.lower() == "base64":
  152. return base64.encodebytes(cipher_text).decode("utf-8").rstrip()
  153. elif code_method.lower() == "hex":
  154. return binascii.b2a_hex(cipher_text).decode("utf-8").rstrip()
  155. else:
  156. return cipher_text.decode("utf-8").rstrip()
  157.  
  158. def decrypt(self, cipher_text, cipher_method, pad_method="", code_method=""):
  159. if cipher_method.upper() == "MODE_ECB":
  160. self.Cipher_MODE_ECB()
  161. elif cipher_method.upper() == "MODE_CBC":
  162. self.Cipher_MODE_CBC()
  163. if code_method.lower() == "base64":
  164. cipher_text = base64.decodebytes(cipher_text.encode("utf-8"))
  165. elif code_method.lower() == "hex":
  166. cipher_text = binascii.a2b_hex(cipher_text.encode("utf-8"))
  167. else:
  168. cipher_text = cipher_text.encode("utf-8")
  169. return self.unpad_method(self.__x.decrypt(cipher_text).decode("utf-8"), pad_method)
  170.  
  171. def text_verify(self, text, method):
  172. while len(text) > len(self.__key):
  173. text_slice = text[:len(self.__key)]
  174. text = text[len(self.__key):]
  175. yield text_slice
  176. else:
  177. if len(text) == len(self.__key):
  178. yield text
  179. else:
  180. yield self.pad_method(text, method)
  181.  
  182. def pad_method(self, text, method):
  183. if method == "":
  184. return Cipher_AES.pad_default(text, len(self.__key))
  185. elif method == "PKCS5Padding":
  186. return Cipher_AES.pad_pkcs5(text, len(self.__key))
  187. else:
  188. return Cipher_AES.pad_user_defined(text, len(self.__key), method)
  189.  
  190. def unpad_method(self, text, method):
  191. if method == "":
  192. return Cipher_AES.unpad_default(text)
  193. elif method == "PKCS5Padding":
  194. return Cipher_AES.unpad_pkcs5(text)
  195. else:
  196. return Cipher_AES.unpad_user_defined(text, method)
  197.  
  198.  
  199.  
  200. def main2(msg, token):
  201. iv = "globalaesvectors"
  202. key = token
  203.  
  204. cipher = Cipher_AES(key=key, iv=iv)
  205. cipher_method = "MODE_CBC"
  206. pad_method = "PKCS5Padding"
  207. code_method = "base64"
  208.  
  209. encrypted_payload = cipher.encrypt(payload, cipher_method=cipher_method, pad_method=pad_method,
  210. code_method=code_method)
  211. decode = cipher.decrypt(encrypted_payload, cipher_method,pad_method, code_method)
  212.  
  213. print(encrypted_payload)
  214. return encrypted_payload
  215.  
  216. if __name__ == '__main__':
  217. import hashlib
  218. import json
  219. payload ={} # some payload
  220. import json
  221. key = '' # key
  222. token = hashlib.sha256(key.encode('utf-8')).hexdigest()[:32]
  223. payload = json.dumps(payload)
  224. x = main2(payload, token)
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Main.java:108: error: illegal start of type
import Crypto.Cipher.AES
^
Main.java:108: error: <identifier> expected
import Crypto.Cipher.AES
                        ^
Main.java:109: error: <identifier> expected
import Crypto.Random
                    ^
Main.java:110: error: <identifier> expected
import base64
             ^
Main.java:111: error: <identifier> expected
import binascii
               ^
Main.java:112: error: <identifier> expected
import hashlib
              ^
Main.java:115: error: '{' expected
class Cipher_AES:
                ^
Main.java:121: error: illegal character: '#'
	# pad_pkcs5=lambda x, y:   "0".encode('utf-8') *(y - len(x) % y)  + x
	^
Main.java:121: error: unclosed character literal
	# pad_pkcs5=lambda x, y:   "0".encode('utf-8') *(y - len(x) % y)  + x
	                                      ^
Main.java:121: error: unclosed character literal
	# pad_pkcs5=lambda x, y:   "0".encode('utf-8') *(y - len(x) % y)  + x
	                                            ^
Main.java:123: error: illegal character: '#'
	# unpad_pkcs5=lambda x: x[-ord(x[-1]):]
	^
Main.java:218: error: unclosed character literal
if __name__ == '__main__':
               ^
Main.java:218: error: unclosed character literal
if __name__ == '__main__':
                        ^
Main.java:221: error: illegal character: '#'
	payload ={} # some payload 
	            ^
Main.java:221: error: <identifier> expected
	payload ={} # some payload 
	                          ^
Main.java:223: error: empty character literal
	key = '' # key 
	      ^
Main.java:223: error: illegal character: '#'
	key = '' # key 
	         ^
Main.java:224: error: unclosed character literal
	token = hashlib.sha256(key.encode('utf-8')).hexdigest()[:32]
	                                  ^
Main.java:224: error: <identifier> expected
	token = hashlib.sha256(key.encode('utf-8')).hexdigest()[:32]
	                                      ^
Main.java:224: error: unclosed character literal
	token = hashlib.sha256(key.encode('utf-8')).hexdigest()[:32]
	                                        ^
Main.java:224: error: invalid method declaration; return type required
	token = hashlib.sha256(key.encode('utf-8')).hexdigest()[:32]
	                                            ^
Main.java:224: error: ';' expected
	token = hashlib.sha256(key.encode('utf-8')).hexdigest()[:32]
	                                                       ^
Main.java:226: error: reached end of file while parsing
	x = main2(payload, token)   
	                         ^
23 errors
stdout
Standard output is empty