我正在尝试进行解密,但我真的不知道 Swift 上的加密技术有多普遍。我在 java 中有这段代码,我必须转换为 Swift,但我没有成功
我正在使用 swift 4.2 和 Java 8
这个函数在java中有效
private static final String CIPHER_NAME = "DESede";
private static final String ALGORITHM = "MD5";
private static final String SECRET_KEY = "p3tr1c0r";
public static String decrypt(String encryptedText) {
String base64EncryptedString;
try{
byte[] message = Base64.decodeBase64(encryptedText.getBytes(StandardCharsets.UTF_8.name()));
MessageDigest md = MessageDigest.getInstance(ALGORITHM);
byte[] digestOfPassword = md.digest(SECRET_KEY.getBytes(StandardCharsets.UTF_8.name()));
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
SecretKey key = new SecretKeySpec(keyBytes, CIPHER_NAME);
Cipher decipher = Cipher.getInstance(CIPHER_NAME);
decipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainText = decipher.doFinal(message);
base64EncryptedString = new String(plainText, StandardCharsets.UTF_8.name());
}catch (UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException ex){
log.warn("Exception while trying to decrypt, using encryptedText ");
base64EncryptedString = encryptedText;
}
return encryptedText;
}
目前我有 md5 摘要的代码,我知道如何转换为 base 64,反之亦然,我的问题是当我想转换字节时,在 java 中,如果我看到日志,字节为负数,但是在swift中是无符号字节,是一样的吗?我的另一个问题是 cipherDesede
,swift 上有类似的东西吗?
let str = "61880868013"
let buf: [UInt8] = Array(str.utf8)
func MD5(string: String) -> Data {
let messageData = string.data(using:.utf8)!
var digestData = Data(count: Int(CC_MD5_DIGEST_LENGTH))
_ = digestData.withUnsafeMutableBytes {digestBytes in
messageData.withUnsafeBytes {messageBytes in
CC_MD5(messageBytes, CC_LONG(messageData.count), digestBytes)
}
}
return digestData
}
在java中输入是uoqrHNWzb4XMQZoTQSGsHQ==
输出为61880868013
最佳答案
in Java if I see the log, the bytes are negative, but in swift are unsigned bytes, is it the same?
是的,它们是一样的。这些位的解释不同,但对于密码学 - 或字符编码/解码 - 只有位值本身很重要。
And my other problem is the cipher DES-EDE, there is something similar on Swift?
Swift 本身似乎并没有做太多的加密,但你可以简单地寻找任何实现:三重 DES/TDES/TDEA/3DES 或实际上 DES-EDE(它们都是一样的)在 ECB 模式下PKCS#5 或 PKCS#7 填充(对于三重 DES 也相同)。
一个链接显示this example which uses CCCrypt underneath ,显然,它似乎被称为 3DES、ECB 和 PKCS#7 填充。
关于java - 是否有像 java 中那样的密码方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55484990/