2 * ============LICENSE_START====================================================
4 * ===========================================================================
5 * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6 * ===========================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END====================================================
22 package org.onap.aaf.cadi;
24 import java.io.ByteArrayInputStream;
25 import java.io.ByteArrayOutputStream;
26 import java.io.DataInputStream;
27 import java.io.DataOutputStream;
29 import java.io.FileInputStream;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.OutputStream;
33 import java.security.SecureRandom;
34 import java.util.ArrayList;
35 import java.util.Random;
37 import javax.crypto.CipherInputStream;
38 import javax.crypto.CipherOutputStream;
40 import org.onap.aaf.cadi.Access.Level;
41 import org.onap.aaf.cadi.config.Config;
44 * Key Conversion, primarily "Base64"
46 * Base64 is required for "Basic Authorization", which is an important part of the overall CADI Package.
48 * Note: This author found that there is not a "standard" library for Base64 conversion within Java.
49 * The source code implementations available elsewhere were surprisingly inefficient, requiring, for
50 * instance, multiple string creation, on a transaction pass. Integrating other packages that might be
51 * efficient enough would put undue Jar File Dependencies given this Framework should have none-but-Java
54 * The essential algorithm is good for a symmetrical key system, as Base64 is really just
55 * a symmetrical key that everyone knows the values.
57 * This code is quite fast, taking about .016 ms for encrypting, decrypting and even .08 for key
58 * generation. The speed quality, especially of key generation makes this a candidate for a short term token
61 * It may be used to easily avoid placing Clear-Text passwords in configurations, etc. and contains
62 * supporting functions such as 2048 keyfile generation (see keygen). This keyfile should, of course,
63 * be set to "400" (Unix) and protected as any other mechanism requires.
65 * However, this algorithm has not been tested against hackers. Until such a time, utilize more tested
66 * packages to protect Data, especially sensitive data at rest (long term).
72 private static final byte[] DOUBLE_EQ = new byte[] {'=','='};
73 public static final String ENC = "enc:";
74 private static final Object LOCK = new Object();
75 private static final SecureRandom random = new SecureRandom();
77 public final char[] codeset;
78 private final int splitLinesAt;
79 private final String encoding;
80 private final Convert convert;
81 private final boolean endEquals;
82 private byte[] keyBytes = null;
83 //Note: AES Encryption is not Thread Safe. It is Synchronized
84 //private AES aes = null; // only initialized from File, and only if needed for Passwords
87 * This is the standard base64 Key Set.
90 public static final Symm base64 = new Symm(
91 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray()
92 ,76, Config.UTF_8,true);
94 public static final Symm base64noSplit = new Symm(
95 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray()
96 ,Integer.MAX_VALUE, Config.UTF_8,true);
99 * This is the standard base64 set suitable for URLs and Filenames
102 public static final Symm base64url = new Symm(
103 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".toCharArray()
104 ,76, Config.UTF_8,true);
107 * A Password set, using US-ASCII
110 public static final Symm encrypt = new Symm(base64url.codeset,1024, "US-ASCII", false);
111 private static final byte[] EMPTY = new byte[0];
114 * A typical set of Password Chars
115 * Note, this is too large to fit into the algorithm. Only use with PassGen
117 private static char passChars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+!@#$%^&*(){}[]?:;,.".toCharArray();
120 private static Symm internalOnly = null;
123 * Use this to create special case Case Sets and/or Line breaks
125 * If you don't know why you need this, use the Singleton Method
130 public Symm(char[] codeset, int split, String charset, boolean useEndEquals) {
131 this.codeset = codeset;
132 splitLinesAt = split;
134 endEquals = useEndEquals;
135 char prev = 0, curr=0, first = 0;
136 int offset=Integer.SIZE; // something that's out of range for integer array
138 // There can be time efficiencies gained when the underlying keyset consists mainly of ordered
139 // data (i.e. abcde...). Therefore, we'll quickly analyze the keyset. If it proves to have
140 // too much entropy, the "Unordered" algorithm, which is faster in such cases is used.
141 ArrayList<int[]> la = new ArrayList<int[]>();
142 for(int i=0;i<codeset.length;++i) {
144 if(prev+1==curr) { // is next character in set
147 if(offset!=Integer.SIZE) { // add previous range
148 la.add(new int[]{first,prev,offset});
154 la.add(new int[]{first,curr,offset});
155 if(la.size()>codeset.length/3) {
156 convert = new Unordered(codeset);
157 } else { // too random to get speed enhancement from range algorithm
158 int[][] range = new int[la.size()][];
160 convert = new Ordered(range);
164 public Symm copy(int lines) {
165 return new Symm(codeset,lines,encoding,endEquals);
168 // Only used by keygen, which is intentionally randomized. Therefore, always use unordered
169 private Symm(char[] codeset, Symm parent) {
170 this.codeset = codeset;
171 splitLinesAt = parent.splitLinesAt;
172 endEquals = parent.endEquals;
173 encoding = parent.encoding;
174 convert = new Unordered(codeset);
178 * Obtain the base64() behavior of this class, for use in standard BASIC AUTH mechanism, etc.
182 public static final Symm base64() {
187 * Obtain the base64() behavior of this class, for use in standard BASIC AUTH mechanism, etc.
192 public static final Symm base64noSplit() {
193 return base64noSplit;
197 * Obtain the base64 "URL" behavior of this class, for use in File Names, etc. (no "/")
200 public static final Symm base64url() {
205 * Obtain a special ASCII version for Scripting, with base set of base64url use in File Names, etc. (no "/")
207 public static final Symm baseCrypt() {
211 public <T> T exec(SyncExec<T> exec) throws Exception {
213 if(keyBytes == null) {
214 keyBytes = new byte[AES.AES_KEY_SIZE/8];
215 int offset = (Math.abs(codeset[0])+47)%(codeset.length-keyBytes.length);
216 for(int i=0;i<keyBytes.length;++i) {
217 keyBytes[i] = (byte)codeset[i+offset];
221 return exec.exec(new AES(keyBytes,0,keyBytes.length));
224 public interface Encryption {
225 public CipherOutputStream outputStream(OutputStream os, boolean encrypt);
226 public CipherInputStream inputStream(InputStream is, boolean encrypt);
229 public static interface SyncExec<T> {
230 public T exec(Encryption enc) throws IOException, Exception;
233 public byte[] encode(byte[] toEncrypt) throws IOException {
234 if(toEncrypt==null) {
237 ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(toEncrypt.length*1.25));
238 encode(new ByteArrayInputStream(toEncrypt),baos);
239 return baos.toByteArray();
243 public byte[] decode(byte[] encrypted) throws IOException {
244 ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(encrypted.length*1.25));
245 decode(new ByteArrayInputStream(encrypted),baos);
246 return baos.toByteArray();
250 * Helper function for String API of "Encode"
251 * use "getBytes" with appropriate char encoding, etc.
255 * @throws IOException
257 public String encode(String str) throws IOException {
259 boolean useDefaultEncoding = false;
261 array = str.getBytes(encoding);
262 } catch (IOException e) {
263 array = str.getBytes(); // take default
264 useDefaultEncoding = true;
266 // Calculate expected size to avoid any buffer expansion copies within the ByteArrayOutput code
267 ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(array.length*1.363)); // account for 4 bytes for 3 and a byte or two more
269 encode(new ByteArrayInputStream(array),baos);
270 if (useDefaultEncoding) {
271 return baos.toString();
273 return baos.toString(encoding);
277 * Helper function for the String API of "Decode"
278 * use "getBytes" with appropriate char encoding, etc.
281 * @throws IOException
283 public String decode(String str) throws IOException {
285 boolean useDefaultEncoding = false;
287 array = str.getBytes(encoding);
288 } catch (IOException e) {
289 array = str.getBytes(); // take default
290 useDefaultEncoding = true;
292 // Calculate expected size to avoid any buffer expansion copies within the ByteArrayOutput code
293 ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(array.length*.76)); // Decoding is 3 bytes for 4. Allocate slightly more than 3/4s
294 decode(new ByteArrayInputStream(array), baos);
295 if (useDefaultEncoding) {
296 return baos.toString();
298 return baos.toString(encoding);
302 * Convenience Function
304 * encode String into InputStream and call encode(InputStream, OutputStream)
308 * @throws IOException
310 public void encode(String string, OutputStream out) throws IOException {
311 encode(new ByteArrayInputStream(string.getBytes()),out);
315 * Convenience Function
317 * encode String into InputStream and call decode(InputStream, OutputStream)
321 * @throws IOException
323 public void decode(String string, OutputStream out) throws IOException {
324 decode(new ByteArrayInputStream(string.getBytes()),out);
327 public void encode(InputStream is, OutputStream os, byte[] prefix) throws IOException {
333 * encode InputStream onto Output Stream
338 * @throws IOException
340 public void encode(InputStream is, OutputStream os) throws IOException {
341 // StringBuilder sb = new StringBuilder((int)(estimate*1.255)); // try to get the right size of StringBuilder from start.. slightly more than 1.25 times
343 int read, idx=0, line=0;
348 if(line>=splitLinesAt) {
352 switch(++idx) { // 1 based reading, slightly faster ++
353 case 1: // ptr is the first 6 bits of read
354 os.write(codeset[read>>2]);
357 case 2: // ptr is the last 2 bits of prev followed by the first 4 bits of read
358 os.write(codeset[((prev & 0x03)<<4) | (read>>4)]);
362 // Char 1 is last 4 bits of prev plus the first 2 bits of read
363 // Char 2 is the last 6 bits of read
364 os.write(codeset[(((prev & 0xF)<<2) | (read>>6))]);
365 if(line==splitLinesAt) { // deal with line splitting for two characters
369 os.write(codeset[(read & 0x3F)]);
375 } else { // deal with any remaining bits from Prev, then pad
377 case 1: // just the last 2 bits of prev
378 os.write(codeset[(prev & 0x03)<<4]);
379 if(endEquals)os.write(DOUBLE_EQ);
381 case 2: // just the last 4 bits of prev
382 os.write(codeset[(prev & 0xF)<<2]);
383 if(endEquals)os.write('=');
392 public void decode(InputStream is, OutputStream os, int skip) throws IOException {
393 if(is.skip(skip)!=skip) {
394 throw new IOException("Error skipping on IOStream in Symm");
400 * Decode InputStream onto OutputStream
403 * @throws IOException
405 public void decode(InputStream is, OutputStream os) throws IOException {
408 while((read = is.read())>=0) {
409 index = convert.convert(read);
411 switch(++idx) { // 1 based cases, slightly faster ++
412 case 1: // index goes into first 6 bits of prev
415 case 2: // write second 2 bits of into prev, write byte, last 4 bits go into prev
416 os.write((byte)(prev|(index>>4)));
419 case 3: // first 4 bits of index goes into prev, write byte, last 2 bits go into prev
420 os.write((byte)(prev|(index>>2)));
423 default: // (3+) | prev and last six of index
424 os.write((byte)(prev|(index&0x3F)));
433 * Interface to allow this class to choose which algorithm to find index of character in Key
437 private interface Convert {
438 public int convert(int read) throws IOException;
442 * Ordered uses a range of orders to compare against, rather than requiring the investigation
443 * of every character needed.
447 private static final class Ordered implements Convert {
448 private int[][] range;
449 public Ordered(int[][] range) {
452 public int convert(int read) throws IOException {
460 for(int i=0;i<range.length;++i) {
461 if(read >= range[i][0] && read<=range[i][1]) {
462 return read-range[i][2];
465 throw new IOException("Unacceptable Character in Stream");
470 * Unordered, i.e. the key is purposely randomized, simply has to investigate each character
471 * until we find a match.
475 private static final class Unordered implements Convert {
476 private char[] codec;
477 public Unordered(char[] codec) {
480 public int convert(int read) throws IOException {
487 for(int i=0;i<codec.length;++i) {
488 if(codec[i]==read)return i;
490 // don't give clue in Encryption mode
491 throw new IOException("Unacceptable Character in Stream");
496 * Generate a 2048 based Key from which we extract our code base
499 * @throws IOException
501 public static byte[] keygen() throws IOException {
502 byte inkey[] = new byte[0x600];
503 new SecureRandom().nextBytes(inkey);
504 ByteArrayOutputStream baos = new ByteArrayOutputStream(0x800);
505 base64url.encode(new ByteArrayInputStream(inkey), baos);
506 return baos.toByteArray();
509 // A class allowing us to be less predictable about significant digits (i.e. not picking them up from the
510 // beginning, and not picking them up in an ordered row. Gives a nice 2048 with no visible patterns.
511 private class Obtain {
517 private Obtain(Symm b64, byte[] key) {
518 skip = Math.abs(key[key.length-13]%key.length);
519 if((key.length&0x1) == (skip&0x1)) { // if both are odd or both are even
522 length = b64.codeset.length;
523 last = 17+length%59; // never start at beginning
528 return Math.abs(key[(++last*skip)%key.length])%length;
533 * Obtain a Symm from "keyfile" (Config.KEYFILE) property
537 * @throws IOException
538 * @throws CadiException
540 public static Symm obtain(Access access) throws CadiException {
541 String keyfile = access.getProperty(Config.CADI_KEYFILE,null);
543 Symm symm = Symm.baseCrypt();
545 File file = new File(keyfile);
547 access.log(Level.INIT, Config.CADI_KEYFILE,"points to",file.getCanonicalPath());
548 } catch (IOException e1) {
549 access.log(Level.INIT, Config.CADI_KEYFILE,"points to",file.getAbsolutePath());
553 FileInputStream fis = new FileInputStream(file);
555 symm = Symm.obtain(fis);
559 } catch (IOException e) {
562 } catch (IOException e) {
563 access.log(e, "Cannot load keyfile");
568 filename = file.getCanonicalPath();
569 } catch (IOException e) {
570 filename = file.getAbsolutePath();
572 throw new CadiException("ERROR: " + filename + " does not exist!");
577 return internalOnly();
578 } catch (IOException e) {
579 throw new CadiException(e);
584 * Create a new random key
586 public Symm obtain() throws IOException {
587 byte inkey[] = new byte[0x800];
588 new SecureRandom().nextBytes(inkey);
589 return obtain(inkey);
593 * Obtain a Symm from 2048 key from a String
597 * @throws IOException
599 public static Symm obtain(String key) throws IOException {
600 return obtain(new ByteArrayInputStream(key.getBytes()));
604 * Obtain a Symm from 2048 key from a Stream
608 * @throws IOException
610 public static Symm obtain(InputStream is) throws IOException {
611 ByteArrayOutputStream baos = new ByteArrayOutputStream();
613 base64url.decode(is, baos);
614 } catch (IOException e) {
616 throw new IOException("Invalid Key");
618 byte[] bkey = baos.toByteArray();
619 if(bkey.length<0x88) { // 2048 bit key
620 throw new IOException("Invalid key");
622 return baseCrypt().obtain(bkey);
626 * Convenience for picking up Keyfile
630 * @throws IOException
632 public static Symm obtain(File f) throws IOException {
633 FileInputStream fis = new FileInputStream(f);
641 * Decrypt into a String
647 * @throws IOException
649 public String enpass(String password) throws IOException {
650 ByteArrayOutputStream baos = new ByteArrayOutputStream();
651 enpass(password,baos);
652 return new String(baos.toByteArray());
656 * Create an encrypted password, making sure that even short passwords have a minimum length.
660 * @throws IOException
662 public void enpass(final String password, final OutputStream os) throws IOException {
663 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
664 DataOutputStream dos = new DataOutputStream(baos);
665 byte[] bytes = password.getBytes();
666 if(this.getClass().getSimpleName().startsWith("base64")) { // don't expose randomization
670 Random r = new SecureRandom();
673 for(int i=0;i<3;++i) {
674 dos.writeByte(b=(byte)r.nextInt());
678 for(int i=0;i<start;++i) {
679 dos.writeByte(r.nextInt());
681 dos.writeInt((int)System.currentTimeMillis());
682 int minlength = Math.min(0x9,bytes.length);
683 dos.writeByte(minlength); // expect truncation
684 if(bytes.length<0x9) {
685 for(int i=0;i<bytes.length;++i) {
686 dos.writeByte(r.nextInt());
687 dos.writeByte(bytes[i]);
689 // make sure it's long enough
690 for(int i=bytes.length;i<0x9;++i) {
691 dos.writeByte(r.nextInt());
698 // 7/21/2016 Jonathan add AES Encryption to the mix
700 exec(new SyncExec<Void>() {
702 public Void exec(Encryption enc) throws Exception {
703 CipherInputStream cis = enc.inputStream(new ByteArrayInputStream(baos.toByteArray()), true);
713 } catch (IOException e) {
715 } catch (Exception e) {
716 throw new IOException(e);
721 * Decrypt a password into a String
727 * @throws IOException
729 public String depass(String password) throws IOException {
730 if(password==null)return null;
731 ByteArrayOutputStream baos = new ByteArrayOutputStream();
732 depass(password,baos);
733 return new String(baos.toByteArray());
744 * @throws IOException
746 public long depass(final String password, final OutputStream os) throws IOException {
747 int offset = password.startsWith(ENC)?4:0;
748 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
749 final ByteArrayInputStream bais = new ByteArrayInputStream(password.getBytes(),offset,password.length()-offset);
751 exec(new SyncExec<Void>() {
753 public Void exec(Encryption enc) throws IOException {
754 CipherOutputStream cos = enc.outputStream(baos, false);
756 cos.close(); // flush
760 } catch (IOException e) {
762 } catch (Exception e) {
763 throw new IOException(e);
766 byte[] bytes = baos.toByteArray();
767 DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
769 if(this.getClass().getSimpleName().startsWith("base64")) { // don't expose randomization
774 for(int i=0;i<3;++i) {
775 start+=Math.abs(dis.readByte());
778 for(int i=0;i<start;++i) {
781 time = (dis.readInt() & 0xFFFF)|(System.currentTimeMillis()&0xFFFF0000);
782 int minlength = dis.readByte();
784 DataOutputStream dos = new DataOutputStream(os);
785 for(int i=0;i<minlength;++i) {
787 dos.writeByte(dis.readByte());
790 int pre =((Byte.SIZE*3+Integer.SIZE+Byte.SIZE)/Byte.SIZE)+start;
791 os.write(bytes, pre, bytes.length-pre);
797 public static String randomGen(int numBytes) {
798 return randomGen(passChars,numBytes);
801 public static String randomGen(char[] chars ,int numBytes) {
803 StringBuilder sb = new StringBuilder(numBytes);
804 for(int i=0;i<numBytes;++i) {
805 rint = random.nextInt(chars.length);
806 sb.append(chars[rint]);
808 return sb.toString();
810 // Internal mechanism for helping to randomize placement of characters within a Symm codeset
811 // Based on an incoming data stream (originally created randomly, but can be recreated within
812 // 2048 key), go after a particular place in the new codeset. If that codeset spot is used, then move
813 // right or left (depending on iteration) to find the next available slot. In this way, key generation
814 // is speeded up by only enacting N iterations, but adds a spreading effect of the random number stream, so that keyset is also
815 // shuffled for a good spread. It is, however, repeatable, given the same number set, allowing for
816 // quick recreation when the official stream is actually obtained.
817 public Symm obtain(byte[] key) throws IOException {
818 int filled = codeset.length;
819 char[] seq = new char[filled];
822 boolean right = true;
824 Obtain o = new Obtain(this,key);
828 if(index<0 || index>=codeset.length) {
829 System.out.println("uh, oh");
831 if(right) { // alternate going left or right to find the next open slot (keeps it from taking too long to hit something)
832 for(int j=index;j<end;++j) {
834 seq[j]=codeset[filled];
841 for(int j=index;j>=0;--j) {
843 seq[j]=codeset[filled];
851 Symm newSymm = new Symm(seq,this);
854 newSymm.keyBytes = new byte[AES.AES_KEY_SIZE/8];
855 int offset = (Math.abs(key[(47%key.length)])+137)%(key.length-newSymm.keyBytes.length);
856 for(int i=0;i<newSymm.keyBytes.length;++i) {
857 newSymm.keyBytes[i] = key[i+offset];
859 } catch (Exception e) {
860 throw new IOException(e);
867 * This Symm is generated for internal JVM use. It has no external keyfile, but can be used
868 * for securing Memory, as it remains the same ONLY of the current JVM
870 * @throws IOException
872 public static synchronized Symm internalOnly() throws IOException {
873 if(internalOnly==null) {
874 ByteArrayInputStream baos = new ByteArrayInputStream(keygen());
876 internalOnly = Symm.obtain(baos);