我有一个 JSON 对象,我从要加密的表单上的 serializeArray 生成。我正在开发的应用程序旨在仅作为本地文件运行。加密数据的最佳选择是什么?
目前,我有一些代码使用本机 OpenSSL 二进制文件使用 SHA256 算法对字节字符串进行签名,该代码调用外部进程,发送参数,并将结果接收回 Python 代码。
当前代码如下:
signed_digest_proc = subprocess.Popen(
['openssl', 'dgst', '-sha256', '-sign', tmp_path],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE
)
signed_digest_proc.stdin.write(original_string)
signed_digest, _ = signed_digest_proc.communicate()
base64.encodestring(signed_digest).decode().replace('\n', '')
Run Code Online (Sandbox Code Playgroud)
当original_string太大时,我可能会遇到结果问题(我认为来自与外部进程的通信),这就是为什么我试图将其更改为仅限 Python 的解决方案:
import hmac, hashlib
h = hmac.new(bytes(key_pem(), 'ASCII'), original_string, hashlib.sha256)
result = base64.encodestring(h).decode().replace('\n', '')
Run Code Online (Sandbox Code Playgroud)
这导致与第一个完全不同的字符串。
在不调用外部进程的情况下实现原始代码的方法是什么?
我想使用此密钥 C6864E7696C686 和 DES 算法加密挑战(如 162236fe0bec620827958c8fdf7e4bc7 )。
这是我的代码:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.xml.bind.DatatypeConverter;
import javax.crypto.spec.DESKeySpec;
def data = prev.getResponseData();
String challenge = javax.xml.bind.DatatypeConverter.printHexBinary(data);
final String strPassPhrase = "C6864E7696C686";
String param = challenge;
System.out.println("Text : " + param);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
SecretKey key = factory.generateSecret(new DESKeySpec(hexStringToByteArray(strPassPhrase)));
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
String str = DatatypeConverter.printBase64Binary(cipher.doFinal(param.getBytes()));
System.out.println("Text Encryted : " + str);
cipher.init(Cipher.DECRYPT_MODE, key);
String str2 = new String(cipher.doFinal(DatatypeConverter.parseBase64Binary(str)));
System.out.println("Text Decryted : " + str2);
Run Code Online (Sandbox Code Playgroud)
但我得到这个例外:
java.security.InvalidKeyException: …Run Code Online (Sandbox Code Playgroud) 我得到java.security.InvalidKeyException: Keystore operation failed. 有没有人有想法?这是我的代码:
initDecodeCipher 的代码:
private static void initDecodeCipher(int mode) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException, InvalidKeyException, NoSuchPaddingException {
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) sKeyStore.getEntry(FINGERPRINT_KEY_NAME, null);
Cipher output = Cipher.getInstance(TRANSFORMATION);
output.init(Cipher.DECRYPT_MODE, privateKeyEntry.getPrivateKey());
}
Run Code Online (Sandbox Code Playgroud)
initEncodeCipher 的代码:
private static void initEncodeCipher(int mode) throws KeyStoreException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
PublicKey key = sKeyStore.getCertificate(FINGERPRINT_KEY_NAME).getPublicKey();
PublicKey unrestricted = KeyFactory.getInstance(key.getAlgorithm()).generatePublic(new X509EncodedKeySpec(key.getEncoded()));
OAEPParameterSpec spec = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);
sCipher.init(mode, unrestricted, spec);
}
Run Code Online (Sandbox Code Playgroud)
生成新密钥的代码:
@TargetApi(Build.VERSION_CODES.M)
private static boolean generateNewKey() {
if (getKeyPairGenerator()) {
try …Run Code Online (Sandbox Code Playgroud) 我正在使用 Pycryptodome(一个 PyCrypto fork)来创建 AES-GCM 密文。我使用以下 Python 代码进行加密:
cek = os.urandom(16)
nonce = os.urandom(12)
cipher = AES.new(cek, AES.MODE_GCM, nonce=nonce, mac_len=16)
ciphertext = cipher.encrypt(message)
Run Code Online (Sandbox Code Playgroud)
然后我将其传递给 Java 进行解密:
byte[] nonce = new byte[12];
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec gcmSpec = new GCMParameterSpec(128, iv);
SecretKeySpec secretKeySpec = new SecretKeySpec(cek, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(nonce);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, gcmSpec);
byte[] decBytes = mCipher.doFinal(cipherText);
Run Code Online (Sandbox Code Playgroud)
但是,我收到以下错误:
Exception in thread "main" javax.crypto.AEADBadTagException: Tag mismatch!
at com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterMode.java:524)
at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1023)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:960)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
Run Code Online (Sandbox Code Playgroud) 我正在现有的文件管理程序中实施本地加密。
我可以找到的许多示例代码,例如Microsoft 的,演示了如何直接写入文件,但我需要做的是提供一个在程序中其他地方使用的流:
CryptoStream GetEncryptStream(string filename)
{
var rjndl = new RijndaelManaged();
rjndl.KeySize = 256;
rjndl.BlockSize = 256;
rjndl.Mode = CipherMode.CBC;
rjndl.Padding = PaddingMode.PKCS7;
// Open read stream of unencrypted source fileStream:
var fileStream = new FileStream(filename, FileMode.Open);
/* Get key and iv */
var transform = rjndl.CreateEncryptor(key, iv);
// CryptoStream in *read* mode:
var cryptoStream = new CryptoStream(fileStream, transform, CryptoStreamMode.Read);
/* What can I do here to insert the unencrypted IV at the start of the
stream …Run Code Online (Sandbox Code Playgroud) 我一直在试图找出解决 Java 安全/加密库的方法,我相信我在理解正在发生的事情方面取得了一些进展。我想我设法让加密部分工作。在我的加密方法中,如果我只是尝试返回,
return new String(encryptedText, "UTF-8");
我会得到一些看起来像加密文本的不可读的混乱。当我尝试而不是返回它时,问题就出现了,继续调用decrypt 并转到明文--> 加密--> 解密这里是我所拥有的一切
import javax.crypto.*;
import java.security.*;
import java.io.UnsupportedEncodingException;
public class AES256_GCM {
public String encrypt(String cleartext) {
try
{
// encoding format needs thought
byte[] clearTextbytes = cleartext.getBytes("UTF-8");
final SecureRandom secureKeyRandomness = SecureRandom.getInstanceStrong();
final KeyGenerator AES_keyInstance = KeyGenerator.getInstance("AES");
AES_keyInstance.init(128, secureKeyRandomness);
final SecretKey secretKey = AES_keyInstance.generateKey();
final Cipher AES_cipherInstance = Cipher.getInstance("AES/GCM/NoPadding");
AES_cipherInstance.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedText = AES_cipherInstance.doFinal(clearTextbytes);
return decrypt(encryptedText, secretKey);
}
catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | …Run Code Online (Sandbox Code Playgroud) 我.pem使用以下命令使用 openssl生成文件:
openssl genrsa -aes256 -out ca.key.pem 4096
Run Code Online (Sandbox Code Playgroud)
它工作得很好,但是当我这样做时:
openssl genrsa -aes256 -out ca.key.pem 4096 -password pass:abcd
Run Code Online (Sandbox Code Playgroud)
它仍然在终端中要求我输入密码,而不是自动使用提供的密码。
我之前尝试过生成证书,它适用于它们,例如。
openssl pkcs12 -name username -inkey cert/key.key -in abc.pem -export -out cert.p12 -password pass:abcd
Run Code Online (Sandbox Code Playgroud) 我有以下 Java 代码
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AESEncryption
{
public static final String AES_TRANSFORMATION = "AES/ECB/PKCS5Padding";
public static final String AES_ALGORITHM = "AES";
public static final int ENC_BITS = 256;
public static final String CHARACTER_ENCODING = "UTF-8";
private static Cipher ENCRYPT_CIPHER;
private static Cipher DECRYPT_CIPHER;
private static KeyGenerator KEYGEN;
static
{
try
{
ENCRYPT_CIPHER = Cipher.getInstance(AES_TRANSFORMATION);
DECRYPT_CIPHER = Cipher.getInstance(AES_TRANSFORMATION);
KEYGEN …Run Code Online (Sandbox Code Playgroud) 我正在使用以下代码片段来加密文本PHP7:
$plaintext = "message to be encrypted";
$cipher = "aes-256-cbc";
$ivlen = openssl_cipher_iv_length($cipher);
$iv = "0123456789012345";
$key = "akshayakshayaksh";
$ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options=0, $iv);
print $ciphertext;
Run Code Online (Sandbox Code Playgroud)
输出:cUXDhOEGz19QEo9XDvMzXkGFmg/YQUnXEqKVpfYtUGo=
现在,当我尝试在其中解密Python3它时,会出现错误:
from Crypto.Cipher import AES
obj2 = AES.new('akshayakshayaksh', AES.MODE_CBC, '0123456789012345')
ciphertext = "cUXDhOEGz19QEo9XDvMzXkGFmg/YQUnXEqKVpfYtUGo="
obj2.decrypt(ciphertext)
Run Code Online (Sandbox Code Playgroud)
回溯(最近一次调用):
文件“<stdin>”,第 1 行,<module>
文件“/anaconda3/lib/python3.6/site-packages/Crypto/Cipher/blockalgo.py”,第 295 行,在解密返回 self._cipher.decrypt(ciphertext) ValueError:输入字符串的长度必须是 16 的倍数
我知道 AES 是一种分组密码算法。但是,我应该如何修复我的 PHP 代码,以便它生成“填充”密码,任何线索?
encryption ×10
java ×5
cryptography ×4
aes ×3
python ×3
php ×2
aes-gcm ×1
android ×1
c# ×1
des ×1
exception ×1
jquery ×1
keystore ×1
openssl ×1
pem ×1
php-openssl ×1
pycrypto ×1
pycryptodome ×1
security ×1
sha256 ×1