Openbravo软件及其衍生产品(例如unicentaopos)具有以下加密实现,可将数据库密码存储在普通配置文件中。
package com.openbravo.pos.util;
import java.io.UnsupportedEncodingException;
import java.security.*;
import javax.crypto.*;
/**
*
* @author JG uniCenta
*/
public class AltEncrypter {
private Cipher cipherDecrypt;
private Cipher cipherEncrypt;
/** Creates a new instance of Encrypter
* @param passPhrase */
public AltEncrypter(String passPhrase) {
try {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(passPhrase.getBytes("UTF8"));
KeyGenerator kGen = KeyGenerator.getInstance("DESEDE");
kGen.init(168, sr);
Key key = kGen.generateKey();
cipherEncrypt = Cipher.getInstance("DESEDE/ECB/PKCS5Padding");
cipherEncrypt.init(Cipher.ENCRYPT_MODE, key);
cipherDecrypt = Cipher.getInstance("DESEDE/ECB/PKCS5Padding");
cipherDecrypt.init(Cipher.DECRYPT_MODE, key);
} catch (UnsupportedEncodingException | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException e) {
}
}
/**
*
* @param str
* @return
*/
public String encrypt(String str) {
try {
return StringUtils.byte2hex(cipherEncrypt.doFinal(str.getBytes("UTF8")));
} catch (UnsupportedEncodingException | BadPaddingException | IllegalBlockSizeException e) {
}
return null;
}
/**
*
* @param str
* @return
*/
public String decrypt(String str) {
try {
return new String(cipherDecrypt.doFinal(StringUtils.hex2byte(str)), "UTF8");
} catch (UnsupportedEncodingException | BadPaddingException | IllegalBlockSizeException e) {
}
return null;
}
}
要加密,使用以下内容(仅加密密码):
config.setProperty("db.user", jtxtDbUser.getText());
AltEncrypter cypher = new AltEncrypter("cypherkey" + jtxtDbUser.getText());
config.setProperty("db.password", "crypt:" + cypher.encrypt(new String(jtxtDbPassword.getPassword())));
要解密,请使用以下内容:
String sDBUser = m_App.getProperties().getProperty("db.user");
String sDBPassword = m_App.getProperties().getProperty("db.password");
if (sDBUser != null && sDBPassword != null && sDBPassword.startsWith("crypt:")) {
AltEncrypter cypher = new AltEncrypter("cypherkey" + sDBUser);
sDBPassword = cypher.decrypt(sDBPassword.substring(6));
}
我正在使用C#中的独立软件模块,我想从该配置文件中读取数据库密码。有关如何实现这一目标的任何建议吗?
通过分析代码,我可以推断出:
db.password =隐窝:XXX
其中XXX是加密密码。
请帮我弄清楚如何解密密码。无需实际读取普通文件的帮助。请假设我已经在C#程序中的变量中存储了用户名和加密密码(没有“crypt:”部分)。
我一直在尝试修改类似问题的现有示例,但他们专注于AES,到目前为止我还没有成功。
基本上,应该构建C#中的以下函数:
private string DecryptPassword(string username, string encryptedPassword)
我该怎么做?
该软件是开源的,可以找到here
一个测试用例:DecryptPassword("mark", "19215E9576DE6A96D5F03FE1D3073DCC")
应该返回密码getmeback
。基本密码短语为cypherkeymark
。我已经在不同的机器上进行了测试,并且使用相同的用户名“哈希”密码总是相同的。
答案 0 :(得分:3)
AltEncrypter
用来从密码中导出密钥的方法非常糟糕。这种方法应该不使用。
首先,它不安全。密钥派生算法不安全,除非它是计算密集型的。相反,请使用scrypt,bcrypt或PBKDF2等算法。
其次,SHA1PRNG算法没有很好地定义。说,“它使用SHA-1”是不够的。哈希的执行频率是多少?它没有标准化;你将无法在另一个平台(如.Net)上请求“SHA1PRNG”,并获得相同的输出。
因此,请废弃这种加密方法,并使用易于理解的人员编写和维护的简单安全的内容。
不幸的是,问题不止于此。 AltEncrypter
实用程序以尽可能最差的方式使用,使用非秘密密钥,可以可逆地加密身份验证密码。这根本不安全。它允许攻击者解密用户密码并将其用于其他系统上的用户帐户。
这几乎就像这个系统的作者想要来创建一个安全灾难。
答案 1 :(得分:1)
这是一张纸条。我无法添加注释,但我认为用于加密的算法不是SHA1。是“DESEDE / ECB / PKCS5Padding”查看创建加密密码的行(获取) cipherEncrypt = Cipher.getInstance(“DESEDE / ECB / PKCS5Padding”);
SHA1PRNG是一个伪随机数生成器,用于生成加密过程中使用的第一个随机数,以便生成“不同”加密,即使加密了相同的纯文本。
另一个重要的事情是用于加密的密钥,我的意思是:
KeyGenerator kGen = KeyGenerator.getInstance("DESEDE");
kGen.init(168, sr);
Key key = kGen.generateKey(); <-- this key
此密钥用于加密和解密,但我看不到它的存储位置。我的意思是它每次都会重生。它应该从某个地方存储和检索而不是重新生成,因为如果没有使用相同的密钥,则无法解密任何密文。
答案 2 :(得分:1)
这是一个使用一些解决方法的答案。
我尝试重新实现SHA1PRNG
提供的GNU实现(opensource),但它没有提供与SUN专有实现相同的结果(所以他们和#39;不同或我以错误的方式实现它)。所以我实现了一个解决方法:调用java程序为我们派生密钥。是的,这非常便宜,但暂时还有工作。如果有人在我的SHA1PRNG实现中看到错误,请告诉我。
首先,这是一个简单的Java程序,它将使用SHA1PRNG
生成器为一个种子派生一个168位密钥。只需在stdout
上输出,空格分隔即可。
import java.io.UnsupportedEncodingException;
import java.security.*;
import javax.crypto.*;
public class PasswordDeriver {
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
if(args.length == 0){
System.out.println("You need to give the seed as the first argument.");
return;
}
//Use Java to generate the key used for encryption and decryption.
String passPhrase = args[args.length-1];
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(passPhrase.getBytes("UTF8"));
KeyGenerator kGen = KeyGenerator.getInstance("DESEDE");
kGen.init(168, sr);
Key key = kGen.generateKey();
//Key is generated, now output it.
//System.out.println("Format: " + key.getFormat());
byte[] k = key.getEncoded();
for(int i=0; i < k.length; i++){
System.out.print(String.format((i == k.length - 1) ? "%X" : "%X ", k[i]));
}
}
}
这保存为PasswordDeriver.java
,使用javac <file>
编译,然后生成的PasswordDeriver.class
放在与此编译程序相同的文件夹中:(实际的C#程序)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;
using System.Diagnostics;
namespace OpenbravoDecrypter
{
class Program
{
static void Main(string[] args)
{
var decrypted = Decrypt("19215E9576DE6A96D5F03FE1D3073DCC", "mark");
Console.ReadLine();
}
static string Decrypt(string ciphertext, string username)
{
//Ciphertext is given as a hex string, convert it back to bytes
if(ciphertext.Length % 2 == 1) ciphertext = "0" + ciphertext; //pad a zero left is necessary
byte[] ciphertext_bytes = new byte[ciphertext.Length / 2];
for(int i=0; i < ciphertext.Length; i+=2)
ciphertext_bytes[i / 2] = Convert.ToByte(ciphertext.Substring(i, 2), 16);
//Get an instance of a tripple-des descryption
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Mode = CipherMode.ECB; //ECB as Cipher Mode
tdes.Padding = PaddingMode.PKCS7; //PKCS7 padding (same as PKCS5, good enough)
byte[] key_bytes = DeriveKeyWorkAround(username);
Console.WriteLine("Derived Key: " + BitConverter.ToString(key_bytes));
//Start the decryption, give it the key, and null for the IV.
var decryptor = tdes.CreateDecryptor(key_bytes, null);
//Decrypt it.
var plain = decryptor.TransformFinalBlock(ciphertext_bytes, 0, ciphertext_bytes.Length);
//Output the result as hex string and as UTF8 encoded string
Console.WriteLine("Plaintext Bytes: " + BitConverter.ToString(plain));
var s = Encoding.UTF8.GetString(plain);
Console.WriteLine("Plaintext UTF-8: " + s);
return s;
}
/* Work around the fact that we don't have a C# implementation of SHA1PRNG by calling into a custom-prepared java file..*/
static byte[] DeriveKeyWorkAround(string username)
{
username = "cypherkey" + username;
string procOutput = "";
//Invoke java on our file
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c java PasswordDeriver \"" + username + "\"";
p.StartInfo.RedirectStandardOutput = true;
p.OutputDataReceived += (e, d) => procOutput += d.Data;
p.StartInfo.UseShellExecute = false;
p.Start();
p.BeginOutputReadLine();
p.WaitForExit();
//Convert it back
byte[] key = procOutput.Split(' ').Select(hex => Convert.ToByte(hex, 16)).ToArray();
return key;
}
/* This function copies the functionality of the GNU Implementation of SHA1PRNG.
* Currently, it's broken, meaning that it doesn't produce the same output as the SUN implenetation of SHA1PRNG.
* Case 1: the GNU implementation is the same as the SUN implementation, and this re-implementation is just wrong somewhere
* Case 2: the GNU implementation is not the same the SUN implementation, therefore you'd need to reverse engineer some existing
* SUN implementation and correct this method.
*/
static byte[] DeriveKey(string username)
{
//adjust
username = "cypherkey" + username;
byte[] user = Encoding.UTF8.GetBytes(username);
//Do SHA1 magic
var sha1 = new SHA1CryptoServiceProvider();
var seed = new byte[20];
byte[] data = new byte[40];
int seedpos = 0;
int datapos = 0;
//init stuff
byte[] digestdata;
digestdata = sha1.ComputeHash(data);
Array.Copy(digestdata, 0, data, 0, 20);
/* seeding part */
for (int i=0; i < user.Length; i++)
{
seed[seedpos++ % 20] ^= user[i];
}
seedpos %= 20;
/* Generate output bytes */
byte[] bytes = new byte[24]; //we need 24 bytes (= 192 bit / 8)
int loc = 0;
while (loc < bytes.Length)
{
int copy = Math.Min(bytes.Length - loc, 20 - datapos);
if (copy > 0)
{
Array.Copy(data, datapos, bytes, loc, copy);
datapos += copy;
loc += copy;
}
else
{
// No data ready for copying, so refill our buffer.
Array.Copy(seed, 0, data, 20, 20);
byte[] digestdata2 = sha1.ComputeHash(data);
Array.Copy(digestdata2, 0, data, 0, 20);
datapos = 0;
}
}
Console.WriteLine("GENERATED KEY:\n");
for(int i=0; i < bytes.Length; i++)
{
Console.Write(bytes[i].ToString("X").PadLeft(2, '0'));
}
return bytes;
}
}
}
你可以看到标准的东西,例如初始化tripple-DES cryptoprovider,给它一个密钥并计算那里密文的解密。它还包含SHA1PRNG
当前损坏的实现和解决方法。鉴于java
位于当前环境变量的PATH
中,此程序将生成输出:
派生钥匙:86-EF-C1-F2-2F-97-D3-F1-34-49-23-89-E3-EC-29-80-02-92-52-40-49-5D- CD-C1
明文字节:67-65-74-6D-65-62-61-63-6B
纯文字UTF-8:getmeback
所以,在这里你有解密功能(加密它会相同,只需将.CreateDecryptor()
更改为.CreateEncryptor()
)。如果您忘记了执行密钥派生的代码,则解密代码仅在大约20行代码中起作用。所以在审核中,我的回答是其他想要100%C#解决这个问题的人的起点。希望这会有所帮助。