我正在尝试将Java中的旧加密/解密重现为Ruby One中的新加密,因为我正在重建整个应用程序。显然,所有这些都以尽快更改此加密。
这是Java代码:
public class MyClass {
private static String algo;
private static SecretKey key;
static {
algo = "AES";
String keyString = "someString";
byte[] decodedKey = Base64.getDecoder().decode(keyString);
key = new SecretKeySpec(decodedKey, 0, decodedKey.length, algo);
}
private static String decrypt(String encrypted) {
try {
Cipher cipher = Cipher.getInstance(algo);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decodedBytes = Base64.getDecoder().decode(encrypted.getBytes());
byte[] original = cipher.doFinal(decodedBytes);
return new String(original);
}
catch (Exception e) {
// Some error
return "bad";
}
}
private static String encrypt(String toEncrypt) {
try {
Cipher cipher = Cipher.getInstance(algo);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
byte[] encryptedValue = Base64.getEncoder().encode(encrypted);
return new String(encryptedValue);
}
catch (Exception e) {
// Some error
return "bad";
}
}
}
Java代码来自这里
我的解密问题。这是我的红宝石代码:
key = Digest::SHA256.digest(key)
aes = OpenSSL::Cipher.new('AES-256-CBC')
aes.decrypt
aes.key = Digest::SHA256.digest(key)
aes.update(secretdata) + aes.final
# => OpenSSL::Cipher::CipherError: bad decrypt
我在做什么错?
" AES"算法描述未完成;它将使用默认的操作和填充方案。在JRE中包含的提供商中,这将默认为ECB和PKCS#7填充(" AES/ECB/PKCS5PADDING"(。这显然是不安全的,因为欧洲央行是不安全的,但是由于依赖此默认值的应用程序无法更改(这是首先违约是错误的原因之一(。
此外,在您提供的代码中,不涉及散列。这是一件好事,因为钥匙上的一个安全哈希不足以提供大量的安全性。将钥匙存储在字符串中几乎是糟糕的,但还不够。但是,关键是基本64编码。
因此,您必须切换到 'AES-256-ECB'
并删除键的双重哈希,然后用64个解码代替。
这并不容易,但这是我这样做的方法。
class ManualEncryption
class << self
attr_accessor :configuration
def config
@configuration ||= Configuration.new
end
def aes
return @aes if @aes
@aes = OpenSSL::Cipher.new(config.algo) # "AES-256-ECB"
@aes
end
def decodedKey
return @decodedKey if @decodedKey
@decodedKey = Base64.decode64(config.key_string) # "mySecretString"
end
def configure
yield(config)
raise 'Algo not specified' unless config.algo
raise 'key not specified' unless config.key_string
end
def encrypt(value)
raise 'No configuration done' unless config.algo && config.key_string
aes_perform('encrypt', value)
end
def decrypt(value)
raise 'No configuration done' unless config.algo && config.key_string
return value unless value
aes_perform('decrypt', value)
end
def aes_perform(status, value)
aes.reset
if status.eql?('encrypt')
aes.encrypt
aes.key = decodedKey
aes_val = aes.update(value) + aes.final
Base64::encode64(aes_val)
else
aes.decrypt
aes.key = decodedKey
decoded_value = Base64::decode64(value)
aes.update(decoded_value) + aes.final
end
end
end
class Configuration
attr_accessor :algo, :key_string
attr_reader :aes
end
end
注意:我仍然有加密问题。它在我的加密价值内创建n
,我不知道为什么。我正在研究它。