Если вы по какой-то причине хотите отделить действие создания и записи, эквивалент Java touch
-
try {
//create a file named "testfile.txt" in the current working directory
File myFile = new File("testfile.txt");
if ( myFile.createNewFile() ) {
System.out.println("Success!");
} else {
System.out.println("Failure!");
}
} catch ( IOException ioe ) { ioe.printStackTrace(); }
createNewFile()
, проверка наличия и файл создаются атомарно. Это может быть полезно, если вы хотите, чтобы вы были создателем файла, прежде чем писать его, например.
Используйте кодировку ASCIIEncoding вместо UnicodeEncoding. PHP использует кодировку ASCII для хэш-расчетов.
FWIW, у меня была аналогичная проблема на Java. Оказалось, что мне пришлось использовать кодировку «UTF-8» для создания тех же SHA1-хэшей в Java, что и функция sha1
, созданная в PHP 5.3.1 (работает на XAMPP Vista).
private static String SHA1(final String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
final MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(text.getBytes("UTF-8"));
return new String(org.apache.commons.codec.binary.Hex.encodeHex(md.digest()));
}
Была та же проблема. Этот код работал для меня:
string encode = secretkey + email;
SHA1 sha1 = SHA1CryptoServiceProvider.Create();
byte[] encodeBytes = Encoding.ASCII.GetBytes(encode);
byte[] encodeHashedBytes = sha1.ComputeHash(passwordBytes);
string pencodeHashed = BitConverter.
ToString(encode HashedBytes).Replace("-", "").ToLowerInvariant();
У меня тоже была эта проблема. Следующий код будет работать.
string dataString = "string to hash";
SHA1 hash = SHA1CryptoServiceProvider.Create();
byte[] plainTextBytes = Encoding.ASCII.GetBytes(dataString);
byte[] hashBytes = hash.ComputeHash(plainTextBytes);
string localChecksum = BitConverter.ToString(hashBytes)
.Replace("-", "").ToLowerInvariant();
Попробуйте следующее! Я думаю, что он отлично поработает:
public static string SHA1Encodeb64(string toEncrypt)
{
//Produce an array of bytes which is the SHA1 hash
byte[] sha1Signature = new byte[40];
byte[] sha = System.Text.Encoding.Default.GetBytes(toEncrypt);
SHA1 sha1 = SHA1Managed.Create();
sha1Signature = sha1.ComputeHash(sha);
/**
* The BASE64 encoding standard's 6-bit alphabet, from RFC 1521,
* plus the padding character at the end.
*/
char[] Base64Chars = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/',
'='
};
//Algorithm to encode the SHA1 hash using Base64
StringBuilder sb = new StringBuilder();
int len = sha1Signature.Length;
int i = 0;
int ival;
while (len >= 3)
{
ival = ((int)sha1Signature[i++] + 256) & 0xff;
ival <<= 8;
ival += ((int)sha1Signature[i++] + 256) & 0xff;
ival <<= 8;
ival += ((int)sha1Signature[i++] + 256) & 0xff;
len -= 3;
sb.Append(Base64Chars[(ival >> 18) & 63]);
sb.Append(Base64Chars[(ival >> 12) & 63]);
sb.Append(Base64Chars[(ival >> 6) & 63]);
sb.Append(Base64Chars[ival & 63]);
}
switch (len)
{
case 0: // No pads needed.
break;
case 1: // Two more output bytes and two pads.
ival = ((int)sha1Signature[i++] + 256) & 0xff;
ival <<= 16;
sb.Append(Base64Chars[(ival >> 18) & 63]);
sb.Append(Base64Chars[(ival >> 12) & 63]);
sb.Append(Base64Chars[64]);
sb.Append(Base64Chars[64]);
break;
case 2: // Three more output bytes and one pad.
ival = ((int)sha1Signature[i++] + 256) & 0xff;
ival <<= 8;
ival += ((int)sha1Signature[i] + 256) & 0xff;
ival <<= 8;
sb.Append(Base64Chars[(ival >> 18) & 63]);
sb.Append(Base64Chars[(ival >> 12) & 63]);
sb.Append(Base64Chars[(ival >> 6) & 63]);
sb.Append(Base64Chars[64]);
break;
}
//Encode the signature using Base64
string base64Sha1Signature = sb.ToString();
return base64Sha1Signature;
}
System.Text.Encoding.Default
является плохой идеей очень при работе со строками и криптографией. Различные платформы используют разные значения по умолчанию (UTF8, ASCII, Unicode), а использование Default
просто делает его еще более сложным (поскольку оно может меняться между системами, конфигурацией и версиями).
– poupou
21 February 2012 в 17:56
byte[] sha1Signature = new byte[40];
, а затем sha1Signature = sha1.ComputeHash(sha);
. Вам не нужно new byte[40]
.
– quantum
27 October 2012 в 02:52
Этот метод в .NET эквивалентен sha1 в php:
string sha1Hash(string password)
{
return string.Join("", SHA1CryptoServiceProvider.Create().ComputeHash(Encoding.UTF8.GetBytes(password)).Select(x => x.ToString("x2")));
}