【发布时间】:2021-04-26 21:16:01
【问题描述】:
我需要从服务器传递给我的 Java 加密字符串在 C++ 中实现一个解密方法。 Java加密方法是这样的:
public String crypt (String strMsg)throws CryptUtilException{
byte bytePosition;
int intMsgLen = strMsg.length();
int intKeyLen = strKey.length();
byte[] aByteMsg = strMsg.getBytes();
byte[] aByteOutMsg = new byte[intMsgLen];
if (intMsgLen==0) {
throw new CryptUtilException("In String is null.");
} else{
for (int i=0; i<intMsgLen; i++) {
bytePosition = (byte) (i%intKeyLen);
aByteOutMsg[i] = (byte)((aByteMsg[i] - iCharOffSet) + (byte) strKey.charAt(bytePosition) + bytePosition);
if (aByteOutMsg [i] < 0) aByteOutMsg [i] = (byte) (aByteOutMsg [i] + 128);
}
String strOutMsg = new String (aByteOutMsg);
return strOutMsg;
}
}
我的同事使用该代码进行加密,使用以下代码解密字符串,并建议我将此 Java 代码复制到我的 C++ 项目中:
public String decrypt (String strMsg)throws CryptUtilException{
byte bytePosition;
int intMsgLen = strMsg.length();
int intKeyLen = strKey.length();
byte[] aByteMsg = strMsg.getBytes();
byte[] aByteOutMsg = new byte[intMsgLen];
if (intMsgLen==0) {
throw new CryptUtilException("In String is null.");
} else{
for (int i=0; i<intMsgLen; i++) {
bytePosition = (byte) (i%intKeyLen);
aByteOutMsg[i] = (byte)((aByteMsg[i] + iCharOffSet) - (byte) strKey.charAt(bytePosition) - bytePosition);
if (aByteOutMsg [i] < 0) aByteOutMsg [i] = (byte) (aByteOutMsg [i] + 128);
}
String strOutMsg = new String (aByteOutMsg);
return strOutMsg;
}
}
我很难做到这一点,因为我找不到复制 Java getBytes() 方法的有效方法。 此外,我有一个非常旧的 C++ 版本,为此我不能使用“byte”或“wstring_convert”方法,而且我不在 Windows 操作系统上工作。
【问题讨论】:
-
您可以使用
operator[]和字符串来获取给定位置的字符。 -
C++ 不是 Java。在 C++ 中,
std::string的内容可以直接访问,就像它是一个容器一样,因为std::string实现了与随机访问容器相同的方法。所以:访问字符串中的字节就像访问std::vector的内容一样。如果有人想将字符串的内容提取到std::vector中,那么只需使用重载构造函数构造std::vector,该构造函数采用开始和结束序列迭代器,然后传入std::string的@ 987654331@ 和end()。但这并不会真正起到多大作用。 -
换句话说,您的
aByteMsg和aByteOutMsg变量在C++ 版本中是不必要的。只需直接从字符串中读取和写入“字节”。另请注意,与 Java 不同,C++ 字符串是可变的。
标签: java c++ linux string encryption