001/*
002 * Syncany, www.syncany.org
003 * Copyright (C) 2011-2016 Philipp C. Heckel <philipp.heckel@gmail.com>
004 *
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU General Public License as published by
007 * the Free Software Foundation, either version 3 of the License, or
008 * (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU General Public License for more details.
014 *
015 * You should have received a copy of the GNU General Public License
016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
017 */
018package org.syncany.crypto;
019
020import javax.crypto.spec.SecretKeySpec;
021
022import org.simpleframework.xml.convert.Converter;
023import org.simpleframework.xml.stream.InputNode;
024import org.simpleframework.xml.stream.OutputNode;
025import org.syncany.util.StringUtil;
026
027/**
028 * Converter to properly encode a {@link SaltedSecretKey} when writing 
029 * an XML. Salt and key are serialized as attributes.
030 * 
031 * @author Christian Roth (christian.roth@port17.de)
032 */
033public class SaltedSecretKeyConverter implements Converter<SaltedSecretKey> {
034        public SaltedSecretKey read(InputNode node) throws Exception {
035                byte[] saltBytes = StringUtil.fromHex(node.getAttribute("salt").getValue());
036                byte[] keyBytes = StringUtil.fromHex(node.getAttribute("key").getValue());
037
038                return new SaltedSecretKey(new SecretKeySpec(keyBytes, CipherParams.MASTER_KEY_DERIVATION_FUNCTION), saltBytes);
039        }
040
041        public void write(OutputNode node, SaltedSecretKey saltedSecretKey) {
042                node.setAttribute("salt", StringUtil.toHex(saltedSecretKey.getSalt()));
043                node.setAttribute("key", StringUtil.toHex(saltedSecretKey.getEncoded()));
044        }
045}