How do you read a CertificatePolicy object from an X509 Certificate in Java? - certificate

I can use a method like this for doing it for a SKID (Subject Key Identifier). What is a comparable way to do this in JAVA, natively (not using any 3rd party libraries like bouncy castle)?
I have an x509 certificate that has this something in it and I want to be able to read this out of the certificate:
"....
[3]: ObjectId: 2.5.29.32 Criticality=false
CertificatePolicies [
[CertificatePolicyId: [5.6.7.8.9.1.2.3.4]
[] ]
]
...
"
...
import sun.security.util.DerInputStream;
import sun.security.util.DerValue;
import sun.security.x509.AuthorityKeyIdentifierExtension;
import sun.security.x509.CertificatePolicyMap;
import sun.security.x509.CertificatePolicySet;
import sun.security.x509.KeyIdentifier;
import sun.security.x509.SubjectKeyIdentifierExtension;
....
private static final String SUBJECT_KEY_ID = "2.5.29.14";
.....
/**
* Get the Subject Key Identifier of the PKI Certificate
*
* #return A String containing the SKID
* #throws CertificateParsingException
*/
public String getSubjectKeyIdentifier()
throws IllegalStateException, CertificateParsingException
{
logger.debug("entered");
// if the variable hasn't yet been initialized with a value, initialize it, else return the existing one.
if (subjectKeyIDString == null)
{
if (cert == null)
{
IllegalStateException ise = new IllegalStateException(ERROR_MSG_NOT_INITIALIZED);
logger.error(ise);
throw ise;
}
byte[] skidCertBytes = cert.getExtensionValue(SUBJECT_KEY_ID);
if (skidCertBytes == null)
{
return null;
}
String skidByteString = null;
try
{
DerValue skidDer = new DerValue(skidCertBytes);
byte[] skidDerBytes = skidDer.getDataBytes();
// create a SubjectKeyIdentifierExtension object
SubjectKeyIdentifierExtension skid = new SubjectKeyIdentifierExtension(Boolean.FALSE, skidDerBytes);
boolean isCritical = skid.isCritical();
logger.debug("isCritical: [" + isCritical + "]");
byte[] skidValueBytes = skid.getExtensionValue();
// go inside the SKID object and get the KID (KeyIdentifier) object
KeyIdentifier kid = new KeyIdentifier(skidValueBytes);
// get the bytes of the object (strips off the first two bytes, type & length bytes)
byte[] kidBytes = kid.getIdentifier();
// convert the KID bytes to a DerValue object
DerValue kidDerValue = new DerValue(kidBytes);
byte[] kidByteValue = kidDerValue.getOctetString();
// get the SKID->KID->string value
skidByteString = byteArrayToHexString(kidByteValue, true);
}
catch (IOException e)
{
logger.error(e);
}
logger.debug(skidByteString);
return skidByteString;
}
else
{
return subjectKeyIDString;
}
}

Related

How to get OAuth 2.0 access token using refresh token in scala

How to get OAuth2.0 access token using refresh token in scala .
Sample code using the HttpsURLConnection, without any libraries
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class Sample_OAuth {
public static void main(String[] args) throws Exception {
Sample_OAuth outhDriver = new Sample_OAuth();
outhDriver.sendRefreshTokenRequestWithOnlyHeader(null);
}
/**
* Send refresh token request to 3rd party with client cred either in body or
* request header.
*
* #param conn
* #param mapListTagToMetaDataName
* #return
* #throws Exception
*/
private Map<String, Object> sendRefreshTokenRequestWithOnlyHeader(Map<String, String> mapListTagToMetaDataName)
throws Exception {
String tokenUrl = "https://xyz.snowflakecomputing.com/oauth/token-request";
URL url = new URL(tokenUrl);
StringBuilder stringBuilder = new StringBuilder();
appendURLParam(stringBuilder, "grant_type", "refresh_token", true);
appendURLParam(stringBuilder, "refresh_token", "ver:2-hint:2065896170862-did:1003-ETMsDgAAAYWAOC1cABRBRVMvQ0JDL1BLQ1M1UGFkZGluZwEAABAAEDu3hgX2UvrDbaMif7uC+ygAAADwoZhxL+aOCvvsmNh0wy0FdNGuDRLCtOq7iQTsZPPmfkRZJnkj3nXgKDxTFeFOmty4ej/O6Fsf17HfNvKdLrqfN3V29FkFQ5S+FktFIznTSjtd7+xaMS+sPEAyey2SFfbSyMvrknjq9F+CQZ50H181OO8Ak4v1uW4ON9Q1UBRd9ywM2Yg5g59hPgy90jtAW0DPQ8gvfAwRJCgg2wzV7tXrQ1H2TQhFEkQH418s5pSNB5V6BSW0fFqOUW3O8X4MmHcWcpTbghZ5aga8+dSKSR8jd2KMmfawyXMdkIYdWEsrpcJozuYDAjFwIT1lkqLxqBnuABQIbwjao0KeWXYU3sYanTb0WoR4Ng==",
false);
String clientRequestType = "Basic Auth Header";
return sendOAuthRequestWithHeader(mapListTagToMetaDataName, url, stringBuilder.toString());
}
private static void appendURLParam(StringBuilder stringBuilder, String name, String value, boolean appendAmpersand)
throws UnsupportedEncodingException {
/*
* if (StringUtil.isNullOrEmptyTrim(name) ||
* StringUtil.isNullOrEmptyTrim(value)) { //log.error(String.
* format("Either Auth attr name : %s or value : %s is Null or empty", name,
* value)); return; }
*/
stringBuilder.append(name);
stringBuilder.append("=");
stringBuilder.append(URLEncoder.encode(value, "UTF-8"));
//stringBuilder.append(value);
if (appendAmpersand) {
stringBuilder.append("&");
}
}
private Map<String, Object> sendOAuthRequestWithHeader(Map<String, String> mapListTagToMetaDataName, URL url,
String postBody) throws Exception {
String clientId = "S0RpOorCRUQOqVncoxc8fXUO22A=";
String client_secret = "MHTOaEmQeLB359K+kEAs/+2ow4AcmqD5/ABckC4E2fQ=";
clientId = clientId + ":" + client_secret;
// Should not be MIME-encode since value is used as a HTTP header and MIME adds
// new lines if over 76 characters
String value = java.util.Base64.getEncoder().encodeToString(clientId.getBytes());
return sendOAuthRequest(url, postBody, value);
}
private Map<String, Object> sendOAuthRequest(URL url, String postBody, String authorizationHeader) throws Exception {
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("POST");
urlConn.addRequestProperty("Accept", "application/json");
if (notNullOrEmptyTrim(authorizationHeader)) {
urlConn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConn.addRequestProperty("Authorization", "Basic " + authorizationHeader);
}
return sendAccessTokenRequest(urlConn, postBody);
}
public Map<String, Object> getToken(String tokenUrl, String requestBody, String authorizationHeader)
throws Exception {
// LOG.info("Request : getToken "+ tokenUrl);
URL url = new URL(tokenUrl);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.addRequestProperty("Accept", "application/json");
if (null != authorizationHeader && !authorizationHeader.isEmpty()) {
urlConnection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.addRequestProperty("Authorization", "Basic " + authorizationHeader);
}
return sendAccessTokenRequest(urlConnection, requestBody);
}
private Map<String, Object> sendAccessTokenRequest(HttpsURLConnection urlConn, String postBody) throws Exception {
// Write to input stream
try {
//optional
enableAllSSLCert(urlConn);
urlConn.setDoOutput(true);
//optional
urlConn.setHostnameVerifier((name, session) -> true);
DataOutputStream outputStream = new DataOutputStream(urlConn.getOutputStream());
outputStream.writeBytes(postBody);
outputStream.flush();
outputStream.close();
int responseCode = urlConn.getResponseCode();
InputStream is = null;
// LOG.info(" response code is:" + responseCode);
if (responseCode >= 200 && responseCode < 400) {
is = urlConn.getInputStream();
} else {
// LOG.error("Error, sendOAuthRequest response code is:" + responseCode);
is = urlConn.getErrorStream();
}
// Read response
String response = null;
if (null != is) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuilder stringBuilder = new StringBuilder();
while (true) {
String line = bufferedReader.readLine();
if (line == null) {
break;
} else {
stringBuilder.append(line);
}
}
response = stringBuilder.toString();
bufferedReader.close();
}
// Logging in case of error
if (responseCode != 200) {
// LOG.error("Get Token error response : " + response);
}
System.out.println(response);
Map<String, Object> retValue = new HashMap<>();
retValue.put("errorCode", responseCode);
retValue.put("token", response);
return retValue;
} catch (Exception exp) {
// LOG.info(" Exception while getting Access Token:", exp);
throw exp;
}
}
public static boolean notNullOrEmptyTrim(String str) {
return !isNullOrEmptyTrim(str);
}
public static boolean isNullOrEmptyTrim(String s) {
return s == null || s.trim().isEmpty();
}
/**
* Enable https client for all SSL cert
*
* #param urlConn
* #throws NoSuchAlgorithmException
* #throws KeyManagementException
*/
private void enableAllSSLCert(HttpsURLConnection urlConn) throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAllTrustManager() }, new java.security.SecureRandom());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = (hostname, session) -> true;
urlConn.setHostnameVerifier(allHostsValid);
}
/**
* Override Trust All trust manager
*/
private class TrustAllTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}

How to encrypt data in one app and decrypt it in different Windows app with RSA keys tied to local system?

I have a setup where I need to encrypt blob of data in one app and decrypt it in different app.
I built a sample app that creates a named CngKey object. Then create a RSACng using CngKey object. Then use RSACng object to do encryption/decryption. What I found is that the key changes across restarts of the application even though it is loaded using the name it was created with. I am lost trying to understand the relation between CngKey and RSACng objects.
Below is snippet of code that describes what I am trying to do:
using System;
using System.IO;
using System.Security.Cryptography;
namespace TPMCrypto
{
class Program
{
static byte[] data = { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
static byte[] privateKey;
private static byte[] encrypted;
private static byte[] decrypted;
static void Main(string[] args)
{
const string MyKey = "MyRSAKey";
CngKey cngKey = null;
string cmd = args.Length > 0 ? args[0] : "";
try
{
CngKeyCreationParameters cng = new CngKeyCreationParameters
{
KeyUsage = CngKeyUsages.AllUsages,
KeyCreationOptions = CngKeyCreationOptions.MachineKey,
Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider
};
if (!CngKey.Exists(MyKey, CngProvider.MicrosoftSoftwareKeyStorageProvider, CngKeyOpenOptions.MachineKey))
{
Console.WriteLine("Creating rsaKey");
cngKey = CngKey.Create(CngAlgorithm.Rsa, MyKey, cng);
}
else
{
Console.WriteLine("Opening rsaKey");
cngKey = CngKey.Open(MyKey, CngProvider.MicrosoftSoftwareKeyStorageProvider, CngKeyOpenOptions.MachineKey);
}
RSACng rsaKey = new RSACng(cngKey)
{
KeySize = 2048
};
privateKey = rsaKey.Key.Export(CngKeyBlobFormat.GenericPrivateBlob);
string prvResult = ByteArrayToHexString(privateKey, 0, privateKey.Length);
Console.WriteLine("\nPrivate key - length = " + privateKey.Length + "\n" + prvResult + "\n");
const string FILE_PATH = #"\temp\tpmtests\encryptedblob.dat";
// Encrypt / decrypt
if (cmd == "readfromfile")
{
Directory.CreateDirectory(Path.GetDirectoryName(FILE_PATH));
encrypted = File.ReadAllBytes(FILE_PATH);
}
else if (cmd == "deletekey")
{
cngKey.Delete();
return;
}
else
{
encrypted = Encrypt(rsaKey, data);
Console.WriteLine("The encrypted blob: ");
Console.WriteLine(ByteArrayToHexString(encrypted, 0, encrypted.Length));
File.WriteAllBytes(FILE_PATH, encrypted);
}
decrypted = Decrypt(rsaKey, encrypted);
bool result = ByteArrayCompare(data, decrypted);
if (result)
Console.WriteLine("Encrypt / decrypt works");
else
Console.WriteLine("Encrypt / decrypt fails");
}
catch (Exception e)
{
Console.WriteLine("Exception " + e.Message);
}
finally
{
if (cngKey != null)
cngKey.Dispose();
}
Console.ReadLine();
}
static bool ByteArrayCompare(byte[] a1, byte[] a2)
{
if (a1.Length != a2.Length)
return false;
for (int i = 0; i < a1.Length; i++)
if (a1[i] != a2[i])
return false;
return true;
}
public static string ByteArrayToHexString(byte[] bytes, int start, int length)
{
string delimitedStringValue = BitConverter.ToString(bytes, start, length);
return delimitedStringValue.Replace("-", "");
}
public static byte[] Sign512(byte[] data, byte[] privateKey)
{
CngKey key = CngKey.Import(privateKey, CngKeyBlobFormat.GenericPrivateBlob);
RSACng crypto = new RSACng(key);
return crypto.SignData(data, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
}
public static bool VerifySignature512(byte[] data, byte[] signature, byte[] publicKey)
{
CngKey key = CngKey.Import(publicKey, CngKeyBlobFormat.GenericPublicBlob);
RSACng crypto = new RSACng(key);
return crypto.VerifyData(data, signature, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
}
public static byte[] Encrypt(byte[] publicKey, byte[] data)
{
CngKey key = CngKey.Import(publicKey, CngKeyBlobFormat.GenericPublicBlob);
RSACng crypto = new RSACng(key);
var result = Encrypt(crypto, data);
return result;
}
public static byte[] Encrypt(RSACng crypto, byte[] data)
{
if (null == crypto)
return null;
var result = crypto.Encrypt(data, RSAEncryptionPadding.OaepSHA512);
return result;
}
public static byte[] Decrypt(byte[] privateKey, byte[] data)
{
CngKey key = CngKey.Import(privateKey, CngKeyBlobFormat.GenericPrivateBlob);
RSACng crypto = new RSACng(key);
var result = Decrypt(crypto, data);
return result;
}
public static byte[] Decrypt(RSACng aKey, byte[] data)
{
if (null == aKey)
return null;
var result = aKey.Decrypt(data, RSAEncryptionPadding.OaepSHA512);
return result;
}
}
}
I am aware of dpapi and how to do this using it. I don't want to use it for this, please don't point me in that direction. I am using CNG flavor of crypto to force C# use NCryptXYZ crypto calls and the desire is to secure the keys in TPM.
Ah, looking at your code again, you've made a goof.
RSACng rsaKey = new RSACng(cngKey)
{
KeySize = 2048
};
Setting the KeySize property on an RSACng does one of two things:
If get_KeySize == value, ignore the input, do nothing.
Else, detach from the current key and the next time the key is used, generate a new key of get_KeySize at the time.
So you're opening an existing key, then discarding it, and generating a new ephemeral key. (Which you could see by checking rsaKey.Key.Name, it won't match your input).
Presumably you did this as a way to create the key with the right size in the first place, but you're too late. The correct way is
CngKeyCreationParameters cng = new CngKeyCreationParameters
{
KeyUsage = CngKeyUsages.AllUsages,
KeyCreationOptions = CngKeyCreationOptions.MachineKey,
Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider,
Parameters =
{
new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.Persist),
},
};

How to fetch unread email using javax.mail pop3 from outlook

I am trying to fetch unread email from Inbox(Outlook.office365.com) and also copy the read message to another folder. But I am getting some of the following issues.
Email is being re-read again, even if we mark the email as being
read programmatically.
Unable to copy an email to another folder even when we open the Inbox is RW(Read&Write) mode.
Attached my code as well.
package com.xyz.mail;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
import javax.mail.search.FlagTerm;
public class ReadEmail {
private static final String TRUE = "true";
private static final String MAIL_POP3_HOST = "mail.pop3.host";
private static final String MAIL_POP3_PORT = "mail.pop3.port";
private static final String MAIL_POP3_STARTTLS_ENABLE = "mail.pop3.starttls.enable";
private static final String MAIL_FOLDER_INBOX = "INBOX";
public static void check(String host, String storeType, String user, String password) throws Exception {
Store store = null;
Folder emailFolder = null;
try {
Properties properties = new Properties();
properties.put(MAIL_POP3_HOST, host);
properties.put(MAIL_POP3_PORT, "995");
properties.put(MAIL_POP3_STARTTLS_ENABLE, TRUE);
Session emailSession = Session.getDefaultInstance(properties);
// create the POP3 store object and connect with the pop server
store = emailSession.getStore(storeType);
store.connect(host, user, password);
emailFolder = store.getFolder(MAIL_FOLDER_INBOX);
emailFolder.open(Folder.READ_WRITE);
Message[] messages = emailFolder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
System.out.println("messages.length---" + messages.length);
if (messages.length == 0) {
System.out.println("No new messages found.");
} else {
for (int i = 0, len = messages.length; i < len; i++) {
Message message = messages[i];
boolean hasAttachments = hasAttachments(message);
if (hasAttachments) {
System.out.println(
"Email #" + (i + 1) + " with subject " + message.getSubject() + " has attachments.");
readAttachment(message);
} else {
System.out.println("Email #" + (i + 1) + " with subject " + message.getSubject()
+ " does not have any attachments.");
continue;
}
Folder copyFolder = store.getFolder("copyData");
if (copyFolder.exists()) {
System.out.println("copy messages...");
copyFolder.copyMessages(messages, emailFolder);
message.setFlag(Flags.Flag.DELETED, true);
}
}
}
} catch (Exception e) {
throw new Exception(e);
} finally {
emailFolder.close(false);
store.close();
}
}
public static void main(String[] args) throws Exception {
String host = "outlook.office365.com";
String username = "emailtest#xyz.com";
String password = "passw0rd{}";
String mailStoreType = "pop3s";
check(host, mailStoreType, username, password);
}
private static boolean hasAttachments(Message msg) throws Exception {
if (msg.isMimeType("multipart/mixed")) {
Multipart mp = (Multipart) msg.getContent();
if (mp.getCount() > 1) {
return true;
}
}
return false;
}
public static void readAttachment(Message message) throws Exception {
Multipart multiPart = (Multipart) message.getContent();
for (int i = 0; i < multiPart.getCount(); i++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
String destFilePath = "/home/user/Documents/" + part.getFileName();
System.out.println("Email attachement ---- " + destFilePath);
FileOutputStream output = new FileOutputStream(destFilePath);
InputStream input = part.getInputStream();
byte[] buffer = new byte[4096];
int byteRead;
while ((byteRead = input.read(buffer)) != -1) {
output.write(buffer, 0, byteRead);
}
output.close();
}
}
}
}
How to I fetch only unread email and copy the email to another folder.
change the protocal to imap and change the prot respecitvely ..using pop3 we can access only inbox that is the reason why you are unable to copy the mail to another folder

Get ExtensionValue from x509Certificate

I use bouncycastle in Java
CertificateFactory.getInstance("X509", "BC")
certFactory.generateCertificate(in)
to generate the cert. It works fine. But when I use
x509Certificate.getExtensionValue("1.2.3.4.5.6.7")
The return value does not match the membersrvc's one.
Did I miss some thing?
With bouncycastle you can do this to extract the ASN1 structure of the extension
public ASN1Primitive getExtensionValue(X509Certificate certificate, String oid) throws IOException {
byte[] bytes = certificate.getExtensionValue(oid);
if (bytes == null) {
return null;
}
ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bytes));
ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
return aIn.readObject();
}
ASN1 is a complex object, you need to parse it to get the desired field. For example to Give back the CA URI meta-data found within the given X509 cert.
public String getIssuerURL(final X509Certificate certificate) throws Exception {
final ASN1ObjectIdentifier ocspAccessMethod = X509ObjectIdentifiers.id_ad_caIssuers;
final byte[] authInfoAccessExtensionValue = certificate.getExtensionValue(Extension.authorityInfoAccess.getId());
if (null == authInfoAccessExtensionValue) {
return null;
}
ASN1InputStream ais1 = null;
ASN1InputStream ais2 = null;
try {
final ByteArrayInputStream bais = new ByteArrayInputStream(authInfoAccessExtensionValue);
ais1 = new ASN1InputStream(bais);
final DEROctetString oct = (DEROctetString) (ais1.readObject());
ais2 = new ASN1InputStream(oct.getOctets());
final AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess.getInstance(ais2.readObject());
final AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
for (AccessDescription accessDescription : accessDescriptions) {
final boolean correctAccessMethod = accessDescription.getAccessMethod().equals(ocspAccessMethod);
if (!correctAccessMethod) {
continue;
}
final GeneralName gn = accessDescription.getAccessLocation();
if (gn.getTagNo() != GeneralName.uniformResourceIdentifier) {
continue;
}
final DERIA5String str = (DERIA5String) ((DERTaggedObject) gn.toASN1Primitive()).getObject();
final String accessLocation = str.getString();
return accessLocation;
}
return null;
} catch (IOException e) {
throw new Exception(e);
} finally {
IOUtils.closeQuietly(ais1);
IOUtils.closeQuietly(ais2);
}
}
To return a human-readable string from an ASN1Primitive
public String getStringFromGeneralName(ASN1Primitive names) throws IOException {
ASN1TaggedObject taggedObject = (ASN1TaggedObject) names ;
return new String(ASN1OctetString.getInstance(taggedObject, false).getOctets(), "ISO-8859-1");
}

displaying an uploded image 404 error

I'm trying to upload an image from the signup form using InscriptionForm.java to check the respectieve fields. The upload has no problem (Thanks to BalusC's tutorials), but, when I try to display the uploaded image, I can't; refering to the HTTP network monitor I got 404 error as response. Also, when I try to enter the above link into the browser's adress bar http://localhost:8080/projetForum/images/bd/Id_21082013184506.png I've got a 404 error.
InscriptionForm.java
public final class InscriptionForm {
private static final String CHAMP_EMAIL = "email";
private static final String CHAMP_PASS = "motdepasse";
private static final String CHAMP_CONF = "confirmation";
private static final String CHAMP_NOM = "nom";
private static final String CHAMP_DESC = "description";
private static final String CHAMP_LOC = "localisation";
private static final String CHAMP_SW = "siteweb";
public static final String CHAMP_IMAGE = "avatar";
public static final String CHAMP_JOURDENAISS = "jourdenaissance";
public static final String CHAMP_MOISDENAISS = "moisdenaissance";
public static final String CHAMP_ANNEEDENAISS = "anneedenaissance";
public static final String CHAMP_DATEDENAISS = "datedenaissance";
public static final int TAILLE_TAMPON = 10240; // 10 ko
public static final String CHEMIN = "E:\\Bibliothèque logicielle\\workspace\\projetForum\\WebContent\\images\\bd\\";
private String resultat;
private static Map<String, String> erreurs = new HashMap<String, String>();
public String getResultat() {
return resultat;
}
public Map<String, String> getErreurs() {
return erreurs;
}
public Utilisateur inscrireUtilisateur(HttpServletRequest request) {
String email = getValeurChamp(request, CHAMP_EMAIL);
String motDePasse = getValeurChamp(request, CHAMP_PASS);
String confirmation = getValeurChamp(request, CHAMP_CONF);
String nom = getValeurChamp(request, CHAMP_NOM);
String description = getValeurChamp(request, CHAMP_DESC);
String localisation = getValeurChamp(request, CHAMP_LOC);
String siteweb = getValeurChamp(request, CHAMP_SW);
String image = getValeurChamp(request, CHAMP_IMAGE);
String jourdenaissance = getValeurChamp(request, CHAMP_JOURDENAISS);
String moisdenaissance = getValeurChamp(request, CHAMP_MOISDENAISS);
String anneedenaissance = getValeurChamp(request, CHAMP_ANNEEDENAISS);
Integer datedenaissance = null;
try {
validationEmail(email);
} catch (Exception e) {
setErreur(CHAMP_EMAIL, e.getMessage());
}
try {
validationMotsDePasse(motDePasse, confirmation);
} catch (Exception e) {
setErreur(CHAMP_PASS, e.getMessage());
}
try {
validationNom(nom);
} catch (Exception e) {
setErreur(CHAMP_NOM, e.getMessage());
}
try {
image = validationImage(request, CHEMIN);
} catch (Exception e) {
setErreur(CHAMP_IMAGE, e.getMessage());
}
if (!jourdenaissance.equals("defaut")
&& !moisdenaissance.equals("defaut")
&& !anneedenaissance.equals("defaut")) {
try {
validationDateDeNaiss(Integer.parseInt(jourdenaissance),
Integer.parseInt(moisdenaissance),
Integer.parseInt(anneedenaissance));
} catch (Exception e) {
setErreur(CHAMP_DATEDENAISS, e.getMessage());
}
datedenaissance = Integer.parseInt((jourdenaissance + ""
+ moisdenaissance + "" + anneedenaissance));
}
if (jourdenaissance.equals("defaut")
&& moisdenaissance.equals("defaut")
&& anneedenaissance.equals("defaut")) {
} else {
setErreur(CHAMP_DATEDENAISS,
"Merci de vérifier votre date de naissance.");
}
Utilisateur utilisateur = new Utilisateur(email, motDePasse, nom,
localisation, siteweb, description, datedenaissance, image);
if (erreurs.isEmpty()) {
resultat = "Succès de l'inscription.";
createORupdate(utilisateur, request);
} else {
resultat = "Échec de l'inscription.";
}
return utilisateur;
}
private String validationImage(HttpServletRequest request, String chemin)
throws Exception {
File uploadFilePath = new File(chemin);
// Validate file.
Object fileObject = request.getAttribute("avatar");
if (fileObject == null) {
// No file uploaded.
throw new Exception("Please select file to upload.");
} else if (fileObject instanceof FileUploadException) {
// File upload is failed.
FileUploadException fileUploadException = (FileUploadException) fileObject;
throw new Exception(fileUploadException.getMessage());
}
// If there are no errors, proceed with writing file.
FileItem fileItem = (FileItem) fileObject;
// Get file name from uploaded file and trim path from it.
// Some browsers (e.g. IE, Opera) also sends the path, which is
// completely irrelevant.
String fileName = FilenameUtils.getName(fileItem.getName());
// Prepare filename prefix and suffix for an unique filename in upload
// folder.
String prefix = FilenameUtils.getBaseName(fileName) + "_";
String suffix = "." + FilenameUtils.getExtension(fileName);
File file = null;
try {
// Prepare unique local file based on file name of uploaded file.
file = File.createTempFile(prefix, suffix, uploadFilePath);
// Write uploaded file to local file.
fileItem.write(file);
} catch (Exception e) {
// Can be thrown by uniqueFile() and FileItem#write().
throw new Exception(e.getMessage());
}
return file.getName();
}
private void setErreur(String champ, String message) {
erreurs.put(champ, message);
}
private static String getValeurChamp(HttpServletRequest request,
String nomChamp) {
String valeur = request.getParameter(nomChamp);
if (valeur == null || valeur.trim().length() == 0) {
return null;
} else {
return valeur;
}
}
private static void createORupdate(Utilisateur u, HttpServletRequest request) {
Session s = HibernateUtils.getSession();
Transaction tx = s.beginTransaction();
Query q = s
.createQuery("from Utilisateur where Utilisateur_email = :email");
q.setString("email", u.getEmail());
Utilisateur userUpdt = (Utilisateur) q.uniqueResult();
if (userUpdt != null) {
userUpdt.setNom(u.getNom());
userUpdt.setEmail(u.getEmail());
userUpdt.setSiteweb(u.getSiteweb());
userUpdt.setLocalisation(u.getLocalisation());
userUpdt.setDescription(u.getDescription());
s.update(userUpdt);
} else {
SimpleDateFormat formater = new SimpleDateFormat(
"dd-MM-yyyy hh:mm:ss");
Date aujourdhui = new Date();
u.setDateInscrit(formater.format(aujourdhui));
s.persist(u);
}
tx.commit();
}
private void validationEmail(String email) throws Exception {
UtilisateurDAO<Utilisateur, String> ud = new UtilisateurDAO<Utilisateur, String>();
if (ud.findByID(email) != null)
throw new Exception("Adresse mail déjà utilisée.");
else if (email == null || ud.findByID(email) != null
|| !email.matches("([^.#]+)(\\.[^.#]+)*#([^.#]+\\.)+([^.#]+)")) {
throw new Exception("Merci de saisir une adresse mail valide.");
}
}
private void validationDateDeNaiss(Integer jj, Integer mm, Integer aaaa)
throws Exception {
switch (mm) {
case 2:
if (jj > 28 && ((aaaa / 4) % 100 == 0 && aaaa % 400 == 0))
throw new Exception(
"Merci de vérifier votre date de naissance.");
break;
case 4:
if (jj == 31)
throw new Exception(
"Merci de vérifier votre date de naissance.");
break;
case 6:
if (jj == 31)
throw new Exception(
"Merci de vérifier votre date de naissance.");
break;
case 9:
if (jj == 31)
throw new Exception(
"Merci de vérifier votre date de naissance.");
break;
case 11:
if (jj == 31)
throw new Exception(
"Merci de vérifier votre date de naissance.");
break;
}
}
private void validationMotsDePasse(String motDePasse, String confirmation)
throws Exception {
if (motDePasse != null && confirmation != null) {
if (!motDePasse.equals(confirmation)) {
throw new Exception(
"Les mots de passe entrés sont différents, merci de les saisir à nouveau.");
} else if (motDePasse.length() < 6) {
throw new Exception(
"Les mots de passe doivent contenir au moins 6 caractères.");
}
} else {
throw new Exception(
"Merci de saisir et confirmer votre mot de passe.");
}
}
private static void validationNom(String nom) throws Exception {
ConfigFDAO<ConfigF, Integer> cfd = new ConfigFDAO<ConfigF, Integer>();
UtilisateurDAO<Utilisateur, String> ud = new UtilisateurDAO<Utilisateur, String>();
if (ud.findByNom(nom) != null)
throw new Exception("Nom d'utilisateur déjà utilisée.");
else if (nom == null
|| nom.length() < cfd.findByID(0).getPseudominsize()
|| nom.length() > cfd.findByID(0).getPseudomaxsize()) {
throw new Exception("Le nom d'utilisateur doit contenir au moins "
+ cfd.findByID(0).getPseudominsize() + " et au maximum "
+ cfd.findByID(0).getPseudomaxsize() + " caractères.");
}
}
private static String getNomFichier(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim()
.replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1)
.substring(filename.lastIndexOf('\\') + 1);
}
}
return null;
}
}
MultipartFilter.java
public class MultipartFilter implements Filter {
// Init
// ---------------------------------------------------------------------------------------
private long maxFileSize;
// Actions
// ------------------------------------------------------------------------------------
/**
* Configure the 'maxFileSize' parameter.
*
* #throws ServletException
* If 'maxFileSize' parameter value is not numeric.
* #see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException {
// Configure maxFileSize.
String maxFileSize = filterConfig.getInitParameter("maxFileSize");
if (maxFileSize != null) {
if (!maxFileSize.matches("^\\d+$")) {
throw new ServletException(
"MultipartFilter 'maxFileSize' is not numeric.");
}
this.maxFileSize = Long.parseLong(maxFileSize);
}
}
/**
* Check the type request and if it is a HttpServletRequest, then parse the
* request.
*
* #throws ServletException
* If parsing of the given HttpServletRequest fails.
* #see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws ServletException, IOException {
// Check type request.
if (request instanceof HttpServletRequest) {
// Cast back to HttpServletRequest.
HttpServletRequest httpRequest = (HttpServletRequest) request;
// Parse HttpServletRequest.
HttpServletRequest parsedRequest = parseRequest(httpRequest);
// Continue with filter chain.
chain.doFilter(parsedRequest, response);
} else {
// Not a HttpServletRequest.
chain.doFilter(request, response);
}
}
/**
* #see javax.servlet.Filter#destroy()
*/
public void destroy() {
// I am a boring method.
}
// Helpers
// ------------------------------------------------------------------------------------
/**
* Parse the given HttpServletRequest. If the request is a multipart
* request, then all multipart request items will be processed, else the
* request will be returned unchanged. During the processing of all
* multipart request items, the name and value of each regular form field
* will be added to the parameterMap of the HttpServletRequest. The name and
* File object of each form file field will be added as attribute of the
* given HttpServletRequest. If a FileUploadException has occurred when the
* file size has exceeded the maximum file size, then the
* FileUploadException will be added as attribute value instead of the
* FileItem object.
*
* #param request
* The HttpServletRequest to be checked and parsed as multipart
* request.
* #return The parsed HttpServletRequest.
* #throws ServletException
* If parsing of the given HttpServletRequest fails.
*/
#SuppressWarnings("unchecked")
// ServletFileUpload#parseRequest() does not return generic type.
private HttpServletRequest parseRequest(HttpServletRequest request)
throws ServletException {
// Check if the request is actually a multipart/form-data request.
if (!ServletFileUpload.isMultipartContent(request)) {
// If not, then return the request unchanged.
return request;
}
// Prepare the multipart request items.
// I'd rather call the "FileItem" class "MultipartItem" instead or so.
// What a stupid name ;)
List<FileItem> multipartItems = null;
try {
// Parse the multipart request items.
multipartItems = new ServletFileUpload(new DiskFileItemFactory())
.parseRequest(request);
// Note: we could use ServletFileUpload#setFileSizeMax() here, but
// that would throw a
// FileUploadException immediately without processing the other
// fields. So we're
// checking the file size only if the items are already parsed. See
// processFileField().
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request: "
+ e.getMessage());
}
// Prepare the request parameter map.
Map<String, String[]> parameterMap = new HashMap<String, String[]>();
// Loop through multipart request items.
for (FileItem multipartItem : multipartItems) {
if (multipartItem.isFormField()) {
// Process regular form field (input
// type="text|radio|checkbox|etc", select, etc).
processFormField(multipartItem, parameterMap);
} else {
// Process form file field (input type="file").
processFileField(multipartItem, request);
}
}
// Wrap the request with the parameter map which we just created and
// return it.
return wrapRequest(request, parameterMap);
}
/**
* Process multipart request item as regular form field. The name and value
* of each regular form field will be added to the given parameterMap.
*
* #param formField
* The form field to be processed.
* #param parameterMap
* The parameterMap to be used for the HttpServletRequest.
*/
private void processFormField(FileItem formField,
Map<String, String[]> parameterMap) {
String name = formField.getFieldName();
String value = formField.getString();
String[] values = parameterMap.get(name);
if (values == null) {
// Not in parameter map yet, so add as new value.
parameterMap.put(name, new String[] { value });
} else {
// Multiple field values, so add new value to existing array.
int length = values.length;
String[] newValues = new String[length + 1];
System.arraycopy(values, 0, newValues, 0, length);
newValues[length] = value;
parameterMap.put(name, newValues);
}
}
/**
* Process multipart request item as file field. The name and FileItem
* object of each file field will be added as attribute of the given
* HttpServletRequest. If a FileUploadException has occurred when the file
* size has exceeded the maximum file size, then the FileUploadException
* will be added as attribute value instead of the FileItem object.
*
* #param fileField
* The file field to be processed.
* #param request
* The involved HttpServletRequest.
*/
private void processFileField(FileItem fileField, HttpServletRequest request) {
if (fileField.getName().length() <= 0) {
// No file uploaded.
request.setAttribute(fileField.getFieldName(), null);
} else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) {
// File size exceeds maximum file size.
request.setAttribute(fileField.getFieldName(),
new FileUploadException(
"File size exceeds maximum file size of "
+ maxFileSize + " bytes."));
// Immediately delete temporary file to free up memory and/or disk
// space.
fileField.delete();
} else {
// File uploaded with good size.
request.setAttribute(fileField.getFieldName(), fileField);
}
}
// Utility (may be refactored to public utility class)
// ----------------------------------------
/**
* Wrap the given HttpServletRequest with the given parameterMap.
*
* #param request
* The HttpServletRequest of which the given parameterMap have to
* be wrapped in.
* #param parameterMap
* The parameterMap to be wrapped in the given
* HttpServletRequest.
* #return The HttpServletRequest with the parameterMap wrapped in.
*/
private static HttpServletRequest wrapRequest(HttpServletRequest request,
final Map<String, String[]> parameterMap) {
return new HttpServletRequestWrapper(request) {
public Map<String, String[]> getParameterMap() {
return parameterMap;
}
public String[] getParameterValues(String name) {
return parameterMap.get(name);
}
public String getParameter(String name) {
String[] params = getParameterValues(name);
return params != null && params.length > 0 ? params[0] : null;
}
public Enumeration<String> getParameterNames() {
return Collections.enumeration(parameterMap.keySet());
}
};
}
}
Thanks in advance.