/*
* This file is part of rockframework.
*
* rockframework is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* rockframework is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>;.
*/
package br.net.woodstock.rockframework.security.crypt.impl;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import br.net.woodstock.rockframework.security.crypt.CrypterException;
import br.net.woodstock.rockframework.security.crypt.CrypterReader;
import br.net.woodstock.rockframework.util.Assert;
import br.net.woodstock.rockframework.xml.dom.XmlDocument;
import br.net.woodstock.rockframework.xml.dom.XmlElement;
public class AsyncCrypterReader implements CrypterReader<AsyncCrypter> {
public AsyncCrypterReader() {
super();
}
@Override
public AsyncCrypter read(final InputStream inputStream) {
Assert.notNull(inputStream, "inputStream");
try {
XmlDocument document = XmlDocument.read(inputStream);
XmlElement root = document.getRoot();
String algorithm = CrypterIOHelper.getElementData(root, CrypterIOHelper.KEY_ALGORITHM_ELEMENT);
KeyFactory factory = KeyFactory.getInstance(algorithm);
PrivateKey privateKey = null;
PublicKey publicKey = null;
byte[] privateKeyBytes = CrypterIOHelper.getKey(root, CrypterIOHelper.PRIVATE_KEY_ELEMENT);
if (privateKeyBytes != null) {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
privateKey = factory.generatePrivate(keySpec);
}
byte[] publicKeyBytes = CrypterIOHelper.getKey(root, CrypterIOHelper.PUBLIC_KEY_ELEMENT);
if (publicKeyBytes != null) {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
publicKey = factory.generatePublic(keySpec);
}
KeyPair keyPair = new KeyPair(publicKey, privateKey);
AsyncCrypter crypter = new AsyncCrypter(keyPair);
return crypter;
} catch (Exception e) {
throw new CrypterException(e);
}
}
}