private static String encrypt(String inputText, String algorithmName) { if (inputText == null || "".equals(inputText.trim())) { throw new IllegalArgumentException("请输入要加密的内容"); } if (algorithmName == null || "".equals(algorithmName.trim())) { algorithmName = "md5"; } String encryptText = null; try { MessageDigest m = MessageDigest.getInstance(algorithmName); m.update(inputText.getBytes("UTF8")); byte[] s = m.digest(); return hex(s); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return encryptText; } /** * 返回十六进制字符串 */ private static String hex(byte[] arr) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < arr.length; ++i) { sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100) .substring(1, 3)); } return sb.toString(); }使用Python重新写
时间: 2024-01-21 20:03:57 浏览: 24
以下是使用Python重新编写的代码:
```python
import hashlib
def encrypt(inputText, algorithmName="md5"):
if not inputText:
raise ValueError("请输入要加密的内容")
algorithmName = algorithmName.lower()
if algorithmName not in hashlib.algorithms_guaranteed:
raise ValueError("不支持的加密算法")
m = hashlib.new(algorithmName)
m.update(inputText.encode("utf-8"))
s = m.digest()
return hex(s)[2:]
def hex(arr):
return ''.join(format(x, '02x') for x in arr)
```
这是一个更加Pythonic的实现,使用了Python内置的hashlib模块来进行加密。函数的参数和返回值与原代码相同。
相关问题
String token = DigestUtil.encrypt(uid + System.currentTimeMillis());
引用中的代码段展示了一个生成MD5加密字符串的方法,其中使用了时间戳和用户输入的参数进行加密。但是给出的代码并没有包含生成token的部分。引用和引用中的代码段展示了两个不同的请求方法,其中也没有涉及到生成token的部分。所以根据给出的引用内容,无法直接回答你关于"String token = DigestUtil.encrypt(uid + System.currentTimeMillis());"的问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [手游SDK-登录](https://blog.csdn.net/kk919535895/article/details/104699489)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
public String encrypt(String text) throws Exception { if (text == null || text.length() == 0) throw new Exception("Empty string"); byte[] encrypted = null; try { cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); encrypted = cipher.doFinal(padString(text).getBytes()); } catch (Exception e) { throw new Exception("[encrypt] " + e.getMessage()); } return bytesToHex(encrypted); }
这是一个使用Java语言实现的加密函数,它接收一个字符串类型的明文text,返回一个经过加密之后的十六进制字符串。具体的加密算法和密钥长度无法从这个函数中直接确定,需要查看代码中的其他部分或者相关的文档。根据代码中的注释,可以猜测它可能使用了对称加密算法,如AES、DES等,但需要查看代码中的keyspec和ivspec才能确认使用的具体算法和参数。