/*
* 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.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.security.PrivateKey;
import java.security.PublicKey;
import org.bouncycastle.openssl.MiscPEMGenerator;
import org.bouncycastle.util.io.pem.PemObjectGenerator;
import org.bouncycastle.util.io.pem.PemWriter;
import br.net.woodstock.rockframework.core.util.Assert;
import br.net.woodstock.rockframework.security.crypt.CrypterException;
import br.net.woodstock.rockframework.security.crypt.CrypterWriter;
public class AsynchronousOpenSSLCrypterWriter implements CrypterWriter<AsynchronousCrypter> {
public AsynchronousOpenSSLCrypterWriter() {
super();
}
@Override
public void write(final AsynchronousCrypter crypter, final OutputStream outputStream) {
Assert.notNull(crypter, "crypter");
Assert.notNull(outputStream, "outputStream");
try {
PrivateKey privateKey = crypter.getPrivateKey();
PublicKey publicKey = crypter.getPublicKey();
boolean addLine = false;
PemWriter writer = new PemWriter(new OutputStreamWriter(outputStream));
if (privateKey != null) {
PemObjectGenerator generator = new MiscPEMGenerator(privateKey);
writer.writeObject(generator);
addLine = true;
}
if (publicKey != null) {
if (addLine) {
outputStream.write(CrypterIOHelper.NEW_LINE.getBytes());
}
PemObjectGenerator generator = new MiscPEMGenerator(publicKey);
writer.writeObject(generator);
}
writer.close();
} catch (IOException e) {
throw new CrypterException(e);
}
}
}