Сервлет 2,5 спецификации:
Несколько сервлетов, выполняющих потоки запроса, могут иметь активный доступ к тому же объекту сессии одновременно. Контейнер должен гарантировать, что управление внутренними структурами данных, представляющими атрибуты сессии, выполняется ориентированным на многопотоковое исполнение способом. Разработчик несет ответственность за ориентированный на многопотоковое исполнение доступ к самим объектам атрибута. Это защитит набор атрибута в объекте HttpSession от параллельного доступа, устраняя возможность для приложения, чтобы заставить тот набор становиться поврежденным.
Это безопасно:
// guaranteed by the spec to be safe
request.getSession().setAttribute("foo", 1);
Это не безопасно:
HttpSession session = request.getSession();
Integer n = (Integer) session.getAttribute("foo");
// not thread safe
// another thread might be have got stale value between get and set
session.setAttribute("foo", (n == null) ? 1 : n + 1);
Это не , гарантировал, что был безопасен:
// no guarantee that same instance will be returned,
// nor that session will lock on "this"
HttpSession session = request.getSession();
synchronized (session) {
Integer n = (Integer) session.getAttribute("foo");
session.setAttribute("foo", (n == null) ? 1 : n + 1);
}
я видел этот последний защищенный подход (включая в книгах J2EE), но он, как гарантируют, не будет работать спецификацией Сервлета. Вы могли использовать идентификатор сессии для создания взаимного исключения , но должен быть лучший подход.
Вот пара функций, которые используют платформу .NET для шифрования и дешифрования строки:
public string EncryptString(string plainText)
{
// Instantiate a new RijndaelManaged object to perform string symmetric encryption
RijndaelManaged rijndaelCipher = new RijndaelManaged();
// Set key and IV
rijndaelCipher.Key = Convert.FromBase64String("ABC");
rijndaelCipher.IV = Convert.FromBase64String("123");
// Instantiate a new MemoryStream object to contain the encrypted bytes
MemoryStream memoryStream = new MemoryStream();
// Instantiate a new encryptor from our RijndaelManaged object
ICryptoTransform rijndaelEncryptor = rijndaelCipher.CreateEncryptor();
// Instantiate a new CryptoStream object to process the data and write it to the
// memory stream
CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelEncryptor, CryptoStreamMode.Write);
// Convert the plainText string into a byte array
byte[] plainBytes = Encoding.ASCII.GetBytes(plainText);
// Encrypt the input plaintext string
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
// Complete the encryption process
cryptoStream.FlushFinalBlock();
// Convert the encrypted data from a MemoryStream to a byte array
byte[] cipherBytes = memoryStream.ToArray();
// Close both the MemoryStream and the CryptoStream
memoryStream.Close();
cryptoStream.Close();
// Convert the encrypted byte array to a base64 encoded string
string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
// Return the encrypted data as a string
return cipherText;
}
public string DecryptString(string cipherText)
{
// Instantiate a new RijndaelManaged object to perform string symmetric encryption
RijndaelManaged rijndaelCipher = new RijndaelManaged();
// Set key and IV
rijndaelCipher.Key = Convert.FromBase64String("ABC");
rijndaelCipher.IV = Convert.FromBase64String("123");
// Instantiate a new MemoryStream object to contain the encrypted bytes
MemoryStream memoryStream = new MemoryStream();
// Instantiate a new encryptor from our RijndaelManaged object
ICryptoTransform rijndaelDecryptor = rijndaelCipher.CreateDecryptor();
// Instantiate a new CryptoStream object to process the data and write it to the
// memory stream
CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelDecryptor, CryptoStreamMode.Write);
// Will contain decrypted plaintext
string plainText = String.Empty;
try
{
// Convert the ciphertext string into a byte array
byte[] cipherBytes = Convert.FromBase64String(cipherText);
// Decrypt the input ciphertext string
cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);
// Complete the decryption process
cryptoStream.FlushFinalBlock();
// Convert the decrypted data from a MemoryStream to a byte array
byte[] plainBytes = memoryStream.ToArray();
// Convert the encrypted byte array to a base64 encoded string
plainText = Encoding.ASCII.GetString(plainBytes, 0, plainBytes.Length);
}
finally
{
// Close both the MemoryStream and the CryptoStream
memoryStream.Close();
cryptoStream.Close();
}
// Return the encrypted data as a string
return plainText;
}
Конечно, я не советую жестко кодировать ключ и вектор инициализации следующим образом :)
You will probably want to dive into the System.Security.Cryptography
namespace. I guess the articles Cryptography Overview, Encrypting Data and Decrypting Data at MSDN could be good starters.