将下面的代码转换为python语言: fun encrypt(str: String, publicKey: String): String { // base64编码的公钥 val decoder = Base64.getDecoder() val decodePublicKey = decoder.decode(publicKey) val pubKey = KeyFactory.getInstance("RSA") .generatePublic(X509EncodedKeySpec(decodePublicKey)) as RSAPublicKey // RSA加密 val cipher = Cipher.getInstance("RSA") cipher.init(Cipher.ENCRYPT_MODE, pubKey) // 加密后进行64位编码 val encoder = Base64.getEncoder() return encoder.encodeToString(cipher.doFinal(str.toByteArray(charset("UTF-8")))) }
时间: 2024-04-18 07:30:16 浏览: 139
def encrypt(str, publicKey):
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
# base64编码的公钥
decoder = base64.b64decode(publicKey)
pubKey = RSA.importKey(decoder)
# RSA加密
cipher = PKCS1_v1_5.new(pubKey)
# 加密后进行64位编码
encoder = base64.b64encode(cipher.encrypt(str.encode("UTF-8")))
return encoder.decode("UTF-8")
相关问题
将以下JAVA代码转为PHP代码:import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class AesTool { public static String encrypt(String str, String key) throws Exception { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); byte[] result = cipher.doFinal(str.getBytes("UTF-8")); return Base64.getEncoder().encodeToString(result); } public static String decrypt(String base64Str, String key) throws Exception { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); cipher.init(Cipher.DECRYPT_MODE, keySpec); byte[] decoded = cipher.doFinal(Base64.getDecoder().decode(base64Str)); return new String(decoded, "UTF-8"); } }
以下是将JAVA代码转换为PHP代码的示例:
```php
<?php
class AesTool {
public static function encrypt($str, $key) {
$cipher = "AES-128-ECB";
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$result = openssl_encrypt($str, $cipher, $key, OPENSSL_RAW_DATA, $iv);
return base64_encode($result);
}
public static function decrypt($base64Str, $key) {
$cipher = "AES-128-ECB";
$base64Str = base64_decode($base64Str);
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$decoded = openssl_decrypt($base64Str, $cipher, $key, OPENSSL_RAW_DATA, $iv);
return $decoded;
}
}
```
在这个PHP代码示例中,我们使用了openssl扩展来实现AES算法的加解密,使用的是128位密钥和ECB模式,并且使用PKCS5Padding对明文进行了补位。
阅读全文