2 * ============LICENSE_START=======================================================
3 * DCAEGEN2-SERVICES-SDK
4 * ================================================================================
5 * Copyright (C) 2018 NOKIA 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=========================================================
20 package org.onap.dcaegen2.services.sdk.security;
22 import java.io.IOException;
24 class EncodePassword {
26 private static final int MAX_PASSWORD_LENGTH = 64 * 1024;
27 private static final int ARGS_LENGTH_PASSWORD_PROVIDED = 1;
28 private final CryptPassword cryptPassword;
29 private final CharsFromStreamReader charsFromStreamReader;
31 public EncodePassword(CryptPassword cryptPassword, CharsFromStreamReader charsFromStreamReader) {
32 this.cryptPassword = cryptPassword;
33 this.charsFromStreamReader = charsFromStreamReader;
37 public static void main(String[] args) {
38 new EncodePassword(new CryptPassword(), new CharsFromStreamReader(MAX_PASSWORD_LENGTH)).run(args);
41 public void run(String[] args) {
43 encodeRawInput(readPassword(args));
44 } catch (IOException ex) {
45 printErrorAndExit(ExitCode.IO_ERROR, "Error while reading the password: " + ex.getMessage());
49 private void encodeRawInput(CharSequence rawPassword) {
50 if (rawPassword == null || rawPassword.length() == 0) {
51 printErrorAndExit(ExitCode.INVALID_PASSWORD, "Password cannot be empty");
53 printWarningIfContainsEndlChars(rawPassword);
54 printResult(cryptPassword.encode(rawPassword));
58 private void printWarningIfContainsEndlChars(CharSequence rawPassword) {
59 if (rawPassword.chars().anyMatch(ch -> ch == '\n' || ch == '\r')) {
60 printWarning("Warning: Password contains end of lines characters.");
64 private CharSequence readPassword(String[] args) throws IOException {
65 return args.length >= ARGS_LENGTH_PASSWORD_PROVIDED
67 : charsFromStreamReader.readPasswordFromStdIn();
70 private void printWarning(String msg) {
71 System.err.println(msg);
74 void printErrorAndExit(ExitCode exitCode, String msg) {
75 System.err.println(msg);
76 System.exit(exitCode.value);
79 private void printResult(String encodedPassword) {
80 System.out.println(encodedPassword);