001/*
002 * jPOS Project [http://jpos.org]
003 * Copyright (C) 2000-2026 jPOS Software SRL
004 *
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (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 Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jpos.security;
020
021import org.bouncycastle.util.encoders.Base64;
022import org.jpos.iso.ISOUtil;
023
024import java.io.IOException;
025import java.io.InputStream;
026import java.nio.ByteBuffer;
027
028@SuppressWarnings("unused")
029public class SystemSeed {
030    public static byte[] getSeed (int l) {
031        return getSeed(0, l);
032    }
033    public static byte[] getSeed (int offset, int l) {
034        ByteBuffer buf = ByteBuffer.allocate(l);
035        while (buf.hasRemaining()) {
036            offset = offset % seed.length;
037            int i = Math.min(l-buf.position(), seed.length - offset);
038            buf.put(seed, offset, i);
039            offset += i;
040        }
041        return buf.array();
042    }
043
044    private static final byte[] seed;
045    static {
046        try {
047            byte[] _s0 = get("/META-INF/q2/.seed");
048            byte[] _s1 = get("/META-INF/.seed");
049            seed = _s1 == null ? _s0 : ISOUtil.xor(_s0, _s1);
050            if (seed == null || seed.length < 16)
051                throw new IllegalArgumentException ("Invalid seed");
052        } catch (IOException e) {
053            throw new IllegalArgumentException("Invalid system configuration");
054        }
055    }
056
057    private static byte[] get (String path) throws IOException {
058        InputStream is = SystemSeed.class.getResourceAsStream(path);
059        if (is != null) {
060            try {
061                byte[] b = new byte[is.available()];
062                is.read(b);
063                return Base64.decode(b);
064            } finally {
065                is.close();
066            }
067        }
068        return null;
069    }
070}