요약: 애초에 인코딩은 꼭 utf8로 설치하고 데이터베이스 생성시 collate는 "C.utf8"로 하자
백업복원으로 재생성할 수 없다면 일일히 수정해야 한다

ALTER TABLE [테이블명]
ALTER COLUMN [컬럼명]
SET DATA TYPE character varying(10) COLLATE "C.utf8";

테스트링크: https://onecompiler.com/postgresql/43pk5sws4

테스트코드

SHOW lc_collate;

SELECT * FROM pg_collation WHERE collname like 'ko%' or collname like '%utf%';

-- create
CREATE TABLE test_table (
  seq SERIAL PRIMARY KEY,
  cd VARCHAR(10) NOT NULL,
  nm VARCHAR(10)  NOT NULL,
  nm2 VARCHAR(10)  NOT NULL COLLATE "C.utf8"
);

-- insert
INSERT INTO test_table (cd, nm, nm2) VALUES ('BROWN', '브라운', '브라운');
INSERT INTO test_table (cd, nm, nm2) VALUES ('FUBAO', '푸바오', '푸바오');
INSERT INTO test_table (cd, nm, nm2) VALUES ('ETC', 'ETC', 'ETC');
INSERT INTO test_table (cd, nm, nm2) VALUES ('NO', '123', '123');

-- fetch 
SELECT a.* FROM test_table as a ORDER BY nm;
SELECT a.* FROM test_table as a ORDER BY nm2;

 

 

이하는 삽질로 얻은 지식 정리

1. 데이터베이스 스키마의 locale 확인

SHOW lc_collate

- 이것은 변경이 불가능하다. 데이터베이스 스키마를 새로 생성해야한다. 그리고 이것으로 기본 정렬된다.

- SELECT * FROM pg_database 에서는 모든 데이터베이스 스키마의 정보를 확인할 수 있고 UPDATE pg_database  SET  어쩌고 해서 수정할 수도 있으나 정렬 자체는 변하지 않았다.

 

2. 해당 스키마에서 사용할 수 있는 collate 확인

SELECT * FROM pg_collation 

한글 윈도우에서 기본 로케일로 설치한 것(이하 윈도우)은 utf8 관련은 전혀 없으나
docker로 설치한 것(이하 도커)은 collname기준 "C.utf8", "en_US.utf8" 두가지 있었다

=> 결론. 윈도우라도 인코딩 utf8로 설치해놔야 배포서버와의 환경차이로 인한 혼란을 줄일 수 있다.

 

3. 2의 테이블에 없는 것은 추가할 수 있다.

https://postgresql.kr/docs/13/sql-createcollation.html

ex) CREATE COLLATION [collation이름] (provider = icu, locale = 'ko_KR.utf8')

 

4. 데이터베이스의 collate를 바꾸지 않고 쿼리문에서 일시적으로 collate를 적용해서 정렬하는 방법

SELECT * FROM [테이블명] ORDER BY [컬럼명] COLLATE "ko-KR-x-icu"

collate 이름은 반드시 쌍따옴표로 해야 하며, 3의 테이블에서 collname컬럼을 사용해야 한다.
그런데 ko로 시작하는 것들로 정렬해보니 영어보다 한글이 먼저 나온다ㅠㅠ

 

'DB' 카테고리의 다른 글

InfluxDB2 backup  (0) 2024.02.06

1. 데이터타입: geography

2. 저장: 

INSERT INTO [테이블명] ([geography컬럼명]) values (geography::Point([위도], [경도], 4326));
-- 4326은 우리가 흔히 사용하는 좌표 CRS임

3. 문자열로 변환 조회
단, 이 경우 "POINT ([경도] [위도])" 형태로 반환되므로, 각각 decimal type의 컬럼으로 저장하는 편이 나았음 (다른 방법이 있을 수 있음)

SELECT convert(nvarchar(50), [geography컬럼명]) as [별칭] FROM [테이블명];
-- POINT ([경도] [위도])

4. 특정 위치를 기준으로 반경 5km 조회하기 - geography 타입을 사용한 이유

-- STDistance는 차이를 미터로 반환함

-- 1. 변수선언이 가능한 경우
DECLARE @Origin GEOGRAPHY
SET @Origin = GEOGRAPHY::Point([위도], [경도])
SELECT * FROM [테이블명] WHERE @Origin.STDistance([geography컬럼명]) <= (5 * 1000);

-- 2. DB에서 바로 조회할 경우.
SELECT * FROM [테이블명] WHERE (SELECT [geography컬럼명] FROM [테이블명] WHERE [관리키컬럼명]=[관리키]).STDistance([geography컬럼명]) <= (5 * 1000);

 

'DB > MSSQL' 카테고리의 다른 글

트리거 소스보기  (0) 2016.10.31
초간단 트리거 문법  (0) 2016.08.24
테이블 명세서 쿼리문  (0) 2014.09.23
0을 나누기 에러 대신 null 반환되도록 하기  (0) 2014.09.19
숫자 앞에 0으로 채우기  (0) 2014.09.04

작년 초에 했었는데 1년 6개월만에 완벽하게 잊어버린 관계로 앞으로 이 사태를 막기 위해 기록으로 남겨둔다. cmd 로 발급하는 방법도 있지만 옵션이 뭐가 복잡하고 어쩌고 해서 알못도 이 방법은 쉽게 가능하니까

 

1. 아무 경로에나 폴더 생성

2. cmd 에서 npm init -y

3. npm i mkcert@1.5.1 (오늘자 기준으로 최근 버전인 3.2는 인증기관 인증서를 설치할때 에러가 발생하기 때문에 과거에 잘 됐던 버전으로 특정함)

4. common js 문법을 쓸거기 때문에 js 파일 하나 생성. main.js로 명명하겠음

5. 코드 작성

const mkcert = require('mkcert')
const fs = require('fs')

// 인증 기관 생성
mkcert
   .createCA({
      organization: '가상의 인증기관이름',
      countryCode: 'KR',
      state: 'SEOUL',
      locality: 'SEOUL',
      validityDays: 365, // 1년
   })
   .then((ca) => {
      fs.writeFileSync('./certs/ca.key', ca.key)
      fs.writeFileSync('./certs/ca.crt', ca.cert)

      // 그런 다음 TLS 인증서를 생성
      mkcert
         .createCert({
            domains: ['127.0.0.1', 'localhost'],
            validityDays: 365,
            caKey: ca.key,
            caCert: ca.cert,
         })
         .then((cert) => {
            fs.writeFileSync('./certs/cert.key', cert.key)
            fs.writeFileSync('./certs/cert.crt', cert.cert)
         })
   })

6. cmd에서 node ./main.js 실행

7. 인증기관 인증서 설치 진행

여기서부터 중요함. 인증기관 인증서 부터 설치를 해야함. 인증기관을 신뢰할 수 있어야 tls 인증서가 문제없다고 판단하여 설치할 수 있기 때문임. ca.crt 실행

 

8. 끝

 

기타정보

1. pem 파일은 crt 파일과 동일하기 때문에 확장자만 바꾸면 된다.

2. fullchain.pem 파일이 필요하다면 ca.crt, cert.crt 파일을 합치면 된다.

3. localhost를 https로 쓰다보면 http로 들어가고 싶어도 웹브라우저가 자동 리다이렉트를 해버려서 불편할 수 있는데 그때는 크롬 기준으로 chrome://net-internals/#hsts 로 접속하여 가장 하단인

여기에 localhost 를 넣어서 삭제하면 된다.

 

그럼 진짜 끝

'Server > 기타' 카테고리의 다른 글

리눅스 폴더별 압축  (0) 2022.06.22
쉘스크립트 - 파일을 폴더 생성 후 이동  (0) 2022.06.22

your system software has rejected this edit

이 오류 메시지가 뜨는 경우 번거로워도 불필요한 프로그램 설치없이 설정하려면 다음과 같은 방법으로 해야 한다.

1. 개발자 옵션을 활성화 한다.
설정 > 휴대전화 정보 > 소프트웨어 정보 > 빌드번호 항목을 연속하여 터치(클릭)하여 개발자 옵션을 활성화 한다.

2. usb 디버깅 모드를 활성화환다.
설정 > 개발자 옵션 > USB 디버깅을 허용으로 설정한다.

3. PC에 Google에서 제공하는 platform-tools를 다운로드 받아 압축을 해제한다. 한글 경로가 없도록 c:나 d: 등의 root에 압축을 해제하는 편이 편리한다.
다운로드: https://developer.android.com/studio/releases/platform-tools?hl=ko

4. 파워쉘이나 cmd를 실행하여 해당 경로로 이동하거나 해당 경로에서 오픈한다. (탐색기에서 shift + 우클릭하여 실행하거나 상단 경로에 cmd 입력 후 엔터 등)

5. 휴대폰을 PC와 연결한다. 충전케이블 말고 반드시 데이터케이블을 이용해야 한다.

6. cmd창에서

adb devices

 

7. 휴대폰 화면에 뜨는 USB 디버깅 확인 메시지에서 허용한다.

8. SetEdit에서 했던 설정을 여기서 입력한다.

adb shell settings put system csc_pref_camera_forced_shuttersound_key 0

 

9. 기본카메라에서 무음으로 사진이 잘 찍히는지 확인한다.

 

원인

이 스킨에는 단축키 적용이 되어 있었다.

w: /admin/entry/post/
e: /admin/skin/edit/
r: /admin/plugin/refererUrlLog/
h: /

그리고 해당키는 input과 textarea 태그를 제외한 곳에서 입력한 경우 발동되도록 액션이 걸려있다.

문제는 이 스킨의 댓글창은 div태그에 ContentEditable속성을 적용하여 만들어졌던 것이었다.

 

해결

스킨 html 편집을 하고 상단의 스크립트에서 getKey 함수의 if문의 조건을 다음과 같은 방식으로 변경한다.

<script>
    //추가 단축키
    var key = new Array();
    key['w'] = "/admin/entry/post/";
    key['e'] = "/admin/skin/edit/";
    key['r'] = "/admin/plugin/refererUrlLog/";
    key['h'] = "/";

    function getKey(keyStroke) {
      if (((event.srcElement.tagName === 'INPUT') || (event.srcElement.tagName === 'TEXTAREA') || (event.srcElement.tagName === 'DIV' && event.srcElement.isContentEditable))===false) {
        isNetscape = (document.layers);
        eventChooser = (isNetscape) ? keyStroke.which : event.keyCode;
        which = String.fromCharCode(eventChooser).toLowerCase();
        for (var i in key)
          if (which == i) window.location = key[i];
      }
    }
    document.onkeypress = getKey;
  </script>

 

'오류노트' 카테고리의 다른 글

IE 엑셀 다운로드 파일 바로열기 에러  (0) 2015.08.17

라든가 error msg=“Unable to gather” 등등

influxdb2에서 발생하는 에러인데

 

원인

나의 경우에는 보안인증서 적용후에 발생했는데 privkey.pem파일을 실행할 수 있는 권한이 없어서 발생한 문제였다.

 

해결

letsencrypt를 기준으로 해당 경로와 파일에 influxdb권한그룹과 계정이 권한을 가질 수 있도록 명령어를 작성하여 해결하였다.

centos기준

기존 파일에 읽기 권한을 부여함

setfacl -m d:user:influxdb:r /etc/letsencrypt/archive/[도메인]/privekey.pem

 

아래의 명령어로 미래에 생성될 파일에도 읽기 권한을 부여함

setfacl -m d:user:influxdb:r /etc/letsencrypt/archive/[도메인]

 

influx cli를 통해서 백업가능하다.

백업 공식문서 https://docs.influxdata.com/influxdb/v2/admin/backup-restore/backup/

influx backup [저장경로] -t [관리자초기토큰]

근데 골때리는게 저 관리자초기토큰이다.

아래의 명령어로 일반적인 관리자토큰으로 기존 토큰 목록을 조회할 수 있는데 influxdb UI와 달리 실제 token 값도 조회가 가능하다.

influx auth list -t [관리자토큰]

여기서 [read:/authorizations write:/authorizations read:/buckets write:/buckets read:/dashboards write:/dashboards read:/orgs write:/orgs read:/sources write:/sources read:/tasks write:/tasks read:/telegrafs write:/telegrafs read:/users write:/users read:/variables write:/variables read:/scrapers write:/scrapers read:/secrets write:/secrets read:/labels write:/labels read:/views write:/views read:/documents write:/documents read:/notificationRules write:/notificationRules read:/notificationEndpoints write:/notificationEndpoints read:/checks write:/checks read:/dbrp write:/dbrp read:/notebooks write:/notebooks read:/annotations write:/annotations read:/remotes write:/remotes read:/replications write:/replications] 이런 권한을 가진 토큰이 바로 저 관리자초기토큰인데 나의 경우에는 이게 없었다.

없는 경우 복원기능으로 복원해야 백업이 가능하다.(는 걸 뒤지고 뒤져서 포럼 어딘가의 답변에서 겨우 찾았다. 공식문서끼리 링크 좀 걸어줬으면 좋겠다.)

관리자초기토큰 복원 공식문서 https://docs.influxdata.com/influxdb/v2/reference/cli/influxd/recovery/auth/create-operator/

influxd recovery auth create-operator --bolt-path [bolt파일경로]
influxd recovery auth create-operator --org [organization이름] --username [관리자아이디] --bolt-path [bolt파일경로]

이 방식으로 관리자초기토큰을 복원하는데 성공했다. 이름은 [관리자아이디]'s Recovery Token
사실 간밤에 복원했을때는 recovery token 뭐 이런거랑 이거랑 2개였는데 오늘 출근하니까 한개는 없어지고 이거만 남았다ㅋㅋㅋ

bolt파일경로는 config.toml 파일에서 확인할 수 있다. config.toml 파일은 centos기준 /etc/influxdb/ 에 있다.

추후에 또 이 문제로 헤맬 수 있을 듯 하여 문서로 남겨놓는다.

 

'DB' 카테고리의 다른 글

postgreSQL 한글정렬 문제  (2) 2025.07.03

돌고 돌아서 현재는 이 정보가 맞다.

출처: https://learn.microsoft.com/en-us/virtualization/windowscontainers/quick-start/set-up-environment?tabs=dockerce#windows-server-1

Invoke-WebRequest -UseBasicParsing "https://raw.githubusercontent.com/microsoft/Windows-Containers/Main/helpful_tools/Install-DockerCE/install-docker-ce.ps1" -o install-docker-ce.ps1
.\install-docker-ce.ps1

원격데스크톱으로 작업중이라 연결이 끊어졌는데 다시 재접속하니 마저 진행하고 잘 완료됨

 

json.asp 

<script language="JScript" runat="server">
    var JSON;
    if (!JSON) {
        JSON = {};
    }
    (function () {
        'use strict';
        function f(n) {
            // Format integers to have at least two digits.
            return n < 10 ? '0' + n : n;
        }
        if (typeof Date.prototype.toJSON !== 'function') {
            Date.prototype.toJSON = function (key) {
                return isFinite(this.valueOf())
                    ? this.getUTCFullYear() + '-' +
                        f(this.getUTCMonth() + 1) + '-' +
                        f(this.getUTCDate()) + 'T' +
                        f(this.getUTCHours()) + ':' +
                        f(this.getUTCMinutes()) + ':' +
                        f(this.getUTCSeconds()) + 'Z'
                    : null;
            };
            String.prototype.toJSON =
                Number.prototype.toJSON =
                Boolean.prototype.toJSON = function (key) {
                    return this.valueOf();
                };
        }
        var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
            escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
            gap,
            indent,
            meta = { // table of character substitutions
                '\b': '\\b',
                '\t': '\\t',
                '\n': '\\n',
                '\f': '\\f',
                '\r': '\\r',
                '"' : '\\"',
                '\\': '\\\\'
            },
            rep;
        function quote(string) {
    // If the string contains no control characters, no quote characters, and no
    // backslash characters, then we can safely slap some quotes around it.
    // Otherwise we must also replace the offending characters with safe escape
    // sequences.
            escapable.lastIndex = 0;
            return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string'
                    ? c
                    : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' : '"' + string + '"';
        }
        function str(key, holder) {
    // Produce a string from holder[key].
            var i, // The loop counter.
                k, // The member key.
                v, // The member value.
                length,
                mind = gap,
                partial,
                value = holder[key];
    // If the value has a toJSON method, call it to obtain a replacement value.
            if (value && typeof value === 'object' &&
                    typeof value.toJSON === 'function') {
                value = value.toJSON(key);
            }
    // If we were called with a replacer function, then call the replacer to
    // obtain a replacement value.
            if (typeof rep === 'function') {
                value = rep.call(holder, key, value);
            }
    // What happens next depends on the value's type.
            switch (typeof value) {
            case 'string':
                return quote(value);
            case 'number':
    // JSON numbers must be finite. Encode non-finite numbers as null.
                return isFinite(value) ? String(value) : 'null';
            case 'boolean':
            case 'null':
    // If the value is a boolean or null, convert it to a string. Note:
    // typeof null does not produce 'null'. The case is included here in
    // the remote chance that this gets fixed someday.
                return String(value);
    // If the type is 'object', we might be dealing with an object or an array or
    // null.
            case 'object':
    // Due to a specification blunder in ECMAScript, typeof null is 'object',
    // so watch out for that case.
                if (!value) {
                    return 'null';
                }
    // Make an array to hold the partial results of stringifying this object value.
                gap += indent;
                partial = [];
    // Is the value an array?
                if (Object.prototype.toString.apply(value) === '[object Array]') {
    // The value is an array. Stringify every element. Use null as a placeholder
    // for non-JSON values.
                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }
    // Join all of the elements together, separated with commas, and wrap them in
    // brackets.
                    v = partial.length === 0
                        ? '[]'
                        : gap
                        ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
                        : '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }
    // If the replacer is an array, use it to select the members to be stringified.
                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        if (typeof rep[i] === 'string') {
                            k = rep[i];
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {
    // Otherwise, iterate through all of the keys in the object.
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }
    // Join all of the member texts together, separated with commas,
    // and wrap them in braces.
                v = partial.length === 0
                    ? '{}'
                    : gap
                    ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
                    : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
            }
        }
    // If the JSON object does not yet have a stringify method, give it one.
        if (typeof JSON.stringify !== 'function') {
            JSON.stringify = function (value, replacer, space) {
    // The stringify method takes a value and an optional replacer, and an optional
    // space parameter, and returns a JSON text. The replacer can be a function
    // that can replace values, or an array of strings that will select the keys.
    // A default replacer method can be provided. Use of the space parameter can
    // produce text that is more easily readable.
                var i;
                gap = '';
                indent = '';
    // If the space parameter is a number, make an indent string containing that
    // many spaces.
                if (typeof space === 'number') {
                    for (i = 0; i < space; i += 1) {
                        indent += ' ';
                    }
    // If the space parameter is a string, it will be used as the indent string.
                } else if (typeof space === 'string') {
                    indent = space;
                }
    // If there is a replacer, it must be a function or an array.
    // Otherwise, throw an error.
                rep = replacer;
                if (replacer && typeof replacer !== 'function' &&
                        (typeof replacer !== 'object' ||
                        typeof replacer.length !== 'number')) {
                    throw new Error('JSON.stringify');
                }
    // Make a fake root object containing our value under the key of ''.
    // Return the result of stringifying the value.
                return str('', {'': value});
            };
        }
    // If the JSON object does not yet have a parse method, give it one.
        if (typeof JSON.parse !== 'function') {
            JSON.parse = function (text, reviver) {
    // The parse method takes a text and an optional reviver function, and returns
    // a JavaScript value if the text is a valid JSON text.
                var j;
                function walk(holder, key) {
    // The walk method is used to recursively walk the resulting structure so
    // that modifications can be made.
                    var k, v, value = holder[key];
                    if (value && typeof value === 'object') {
                        for (k in value) {
                            if (Object.prototype.hasOwnProperty.call(value, k)) {
                                v = walk(value, k);
                                if (v !== undefined) {
                                    value[k] = v;
                                } else {
                                    delete value[k];
                                }
                            }
                        }
                    }
                    return reviver.call(holder, key, value);
                }
    // Parsing happens in four stages. In the first stage, we replace certain
    // Unicode characters with escape sequences. JavaScript handles many characters
    // incorrectly, either silently deleting them, or treating them as line endings.
                text = String(text);
                cx.lastIndex = 0;
                if (cx.test(text)) {
                    text = text.replace(cx, function (a) {
                        return '\\u' +
                            ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                    });
                }
    // In the second stage, we run the text against regular expressions that look
    // for non-JSON patterns. We are especially concerned with '()' and 'new'
    // because they can cause invocation, and '=' because it can cause mutation.
    // But just to be safe, we want to reject all unexpected forms.
    // We split the second stage into 4 regexp operations in order to work around
    // crippling inefficiencies in IE's and Safari's regexp engines. First we
    // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
    // replace all simple value tokens with ']' characters. Third, we delete all
    // open brackets that follow a colon or comma or that begin the text. Finally,
    // we look to see that the remaining characters are only whitespace or ']' or
    // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
                if (/^[\],:{}\s]*$/
                        .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
                            .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                            .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
    // In the third stage we use the eval function to compile the text into a
    // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
    // in JavaScript: it can begin a block or an object literal. We wrap the text
    // in parens to eliminate the ambiguity.
                    j = eval('(' + text + ')');
    // In the optional fourth stage, we recursively walk the new structure, passing
    // each name/value pair to a reviver function for possible transformation.
                    return typeof reviver === 'function'
                        ? walk({'': j}, '')
                        : j;
                }
    // If the text is not JSON parseable, then a SyntaxError is thrown.
                throw new SyntaxError('JSON.parse');
            };
        }
    }());
</script>

출처: 쿠팡 https://developers.coupangcorp.com/hc/en-us/articles/360033396834-Classic-ASP-Example 최하단 제공하는 소스압축 파일내 존재함

 

<!--#include file="json.asp"-->
<%
	Call Response.AddHeader("Access-Control-Allow-Origin", "*") ' cors
	Response.ContentType = "application/json"

	dim bytes,binary,reqbody
	bytes=Request.TotalBytes
	binary=Request.BinaryRead(bytes)

	set stream = Server.CreateObject("Adodb.Stream")
	stream.type = 1
	stream.open
	stream.write(binary)
	stream.position = 0
	stream.type = 2
	stream.charset = "utf-8"
	reqbody=stream.readtext()
	stream.close
	set stream = nothing

	dim params
	set params = JSON.parse(reqbody)
%>
	json이 { "id": "test", "age": 100, "group": { "group_name": "dev" } }라고 치면
    params.id
    params.age
    params.group.group_name
    으로 접근가능함
<%   
	set params = nothing	
%>

'Classic ASP' 카테고리의 다른 글

Baisc Auth  (0) 2023.11.01
엑셀 xlsx 읽어들여 DB에 저장하기  (0) 2016.12.05
파일 복사  (0) 2016.11.08
스케쥴러  (0) 2016.09.23
숫자 관련 추가 함수  (0) 2016.06.27
<%
' Decodes a base-64 encoded string (BSTR type).
' 1999 - 2004 Antonin Foller, http://www.motobit.com
' 1.01 - solves problem with Access And 'Compare Database' (InStr)
Function Base64Decode(ByVal base64String)
  'rfc1521
  '1999 Antonin Foller, Motobit Software, http://Motobit.cz
  Const Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
  Dim dataLength, sOut, groupBegin
  
  'remove white spaces, If any
  base64String = Replace(base64String, vbCrLf, "")
  base64String = Replace(base64String, vbTab, "")
  base64String = Replace(base64String, " ", "")
  
  'The source must consists from groups with Len of 4 chars
  dataLength = Len(base64String)
  If dataLength Mod 4 <> 0 Then
    Err.Raise 1, "Base64Decode", "Bad Base64 string."
    Exit Function
  End If

  
  ' Now decode each group:
  For groupBegin = 1 To dataLength Step 4
    Dim numDataBytes, CharCounter, thisChar, thisData, nGroup, pOut
    ' Each data group encodes up To 3 actual bytes.
    numDataBytes = 3
    nGroup = 0

    For CharCounter = 0 To 3
      ' Convert each character into 6 bits of data, And add it To
      ' an integer For temporary storage.  If a character is a '=', there
      ' is one fewer data byte.  (There can only be a maximum of 2 '=' In
      ' the whole string.)

      thisChar = Mid(base64String, groupBegin + CharCounter, 1)

      If thisChar = "=" Then
        numDataBytes = numDataBytes - 1
        thisData = 0
      Else
        thisData = InStr(1, Base64, thisChar, vbBinaryCompare) - 1
      End If
      If thisData = -1 Then
        Err.Raise 2, "Base64Decode", "Bad character In Base64 string."
        Exit Function
      End If

      nGroup = 64 * nGroup + thisData
    Next
    
    'Hex splits the long To 6 groups with 4 bits
    nGroup = Hex(nGroup)
    
    'Add leading zeros
    nGroup = String(6 - Len(nGroup), "0") & nGroup
    
    'Convert the 3 byte hex integer (6 chars) To 3 characters
    pOut = Chr(CByte("&H" & Mid(nGroup, 1, 2))) + _
      Chr(CByte("&H" & Mid(nGroup, 3, 2))) + _
      Chr(CByte("&H" & Mid(nGroup, 5, 2)))
    
    'add numDataBytes characters To out string
    sOut = sOut & Left(pOut, numDataBytes)
  Next

  Base64Decode = sOut
End Function
%>

<%
Dim UID, PWD
GetUser UID, PWD
If UID <> "아이디" or PWD <> "비밀번호" Then
  Response.Status = "401 Access Denied"
End If

Sub GetUser(LOGON_USER, LOGON_PASSWORD)
  Dim UP, Pos, Auth
  Auth = Request.ServerVariables("HTTP_AUTHORIZATION")
  LOGON_USER = ""
  LOGON_PASSWORD = ""
  If LCase(Left(Auth, 5)) = "basic" Then
    UP = Base64Decode(Mid(Auth, 7))
    Pos = InStr(UP, ":")
    If Pos > 1 Then
      LOGON_USER = Left(UP, Pos - 1)
      LOGON_PASSWORD = Mid(UP, Pos + 1)
    End If
  End If
End Sub
%>

 

 

출처: https://www.motobit.com/tips/detpg_base64/

'Classic ASP' 카테고리의 다른 글

request body json data parsing  (1) 2023.11.01
엑셀 xlsx 읽어들여 DB에 저장하기  (0) 2016.12.05
파일 복사  (0) 2016.11.08
스케쥴러  (0) 2016.09.23
숫자 관련 추가 함수  (0) 2016.06.27

+ Recent posts